国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

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

2019-11-26 15:44:35
字體:
供稿:網(wǎng)友

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

復(fù)制代碼 代碼如下:

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是沒有幫你處理線程阻塞問題的,需要手動處理。
處理后:

復(fù)制代碼 代碼如下:

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 類如下:

復(fù)制代碼 代碼如下:

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,就不會阻塞了。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 呼和浩特市| 甘德县| 雷州市| 水城县| 和顺县| 高要市| 台中县| 琼海市| 山东省| 阜南县| 新乐市| 双流县| 平邑县| 鹤山市| 历史| 华宁县| 察雅县| 灌阳县| 讷河市| 德江县| 湘潭市| 高淳县| 韶山市| 荥经县| 泰州市| 略阳县| 大洼县| 荔浦县| 泗阳县| 诏安县| 台南市| 元氏县| 平舆县| 江孜县| 常州市| 漳浦县| 泗水县| 登封市| 曲周县| 浦县| 澳门|