国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 新丰县| 专栏| 辽源市| 平塘县| 西贡区| 天水市| 汝南县| 锦州市| 广昌县| 大渡口区| 怀安县| 沂南县| 茌平县| 濮阳县| 屏东县| 泰顺县| 襄垣县| 吴忠市| 烟台市| 天津市| 太康县| 大丰市| 永川市| 会宁县| 新竹县| 新野县| 武宣县| 白水县| 搜索| 淮安市| 松原市| 新晃| 禄丰县| 屯昌县| 柳林县| 拉萨市| 油尖旺区| 关岭| 莎车县| 班玛县| 承德县|