最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java執(zhí)行bat命令碰到的阻塞問題的解決方法

 更新時間:2014年01月21日 17:38:00   作者:  
這篇文章主要介紹了java執(zhí)行bat命令碰到的阻塞問題的解決方法,有需要的朋友可以參考一下

使用Java來執(zhí)行bat命令,如果bat操作時間過長,有可能導致阻塞問題,而且不會執(zhí)行bat直到關閉服務器。
如:

復制代碼 代碼如下:

Runtime r=Runtime.getRuntime(); 
        Process p=null; 
        try{ 
            String path = "D:/test.bat"; 
     p = r.exec("cmd.exe /c  "+path); 
     p.waitFor(); 
 }catch(Exception e){  
     System.out.println("運行錯誤:"+e.getMessage()); 
     e.printStackTrace();  

一般java的exec是沒有幫你處理線程阻塞問題的,需要手動處理。
處理后:

復制代碼 代碼如下:

Runtime r=Runtime.getRuntime(); 
        Process p=null; 
        try{ 
            String path = "D:/test.bat"; 
     p = r.exec("cmd.exe /c  "+path); 
     StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), "ERROR");          
            errorGobbler.start(); 
            StreamGobbler outGobbler = new StreamGobbler(p.getInputStream(), "STDOUT"); 
            outGobbler.start(); 
     p.waitFor(); 
    }catch(Exception e){  
            System.out.println("運行錯誤:"+e.getMessage()); 
            e.printStackTrace();  
   } 

StreamGobbler 類如下:

復制代碼 代碼如下:

package com.test.tool; 

 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.PrintWriter; 

 
/**
 * 用于處理Runtime.getRuntime().exec產(chǎn)生的錯誤流及輸出流
 */ 
public class StreamGobbler extends Thread { 
    InputStream is; 
    String type; 
    OutputStream os; 

    StreamGobbler(InputStream is, String type) { 
        this(is, type, null); 
    } 

    StreamGobbler(InputStream is, String type, OutputStream redirect) { 
        this.is = is; 
        this.type = type; 
        this.os = redirect; 
    } 

    public void run() { 
        InputStreamReader isr = null; 
        BufferedReader br = null; 
        PrintWriter pw = null; 
        try { 
            if (os != null) 
                pw = new PrintWriter(os); 

            isr = new InputStreamReader(is); 
            br = new BufferedReader(isr); 
            String line=null; 
            while ( (line = br.readLine()) != null) { 
                if (pw != null) 
                    pw.println(line); 
                System.out.println(type + ">" + line);     
            } 

            if (pw != null) 
                pw.flush(); 
        } catch (IOException ioe) { 
            ioe.printStackTrace();   
        } finally{ 
            try { 
                pw.close(); 
                br.close(); 
                isr.close(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 
}  

運行bat,就不會阻塞了。

相關文章

最新評論

磴口县| 汝阳县| 女性| 弋阳县| 广灵县| 宝坻区| 天峻县| 连南| 闽清县| 襄垣县| 拉萨市| 柳林县| 安西县| 深圳市| 禄丰县| 大庆市| 阳西县| 华池县| 孝义市| 东港市| 周宁县| 桑植县| 德阳市| 犍为县| 霍山县| 绵阳市| 岗巴县| 临漳县| 江达县| 峨眉山市| 武义县| 天镇县| 潮州市| 祁门县| 吕梁市| 广灵县| 黔西县| 吴川市| 德清县| 北票市| 五原县|