java执行bat命令碰到的阻塞问题的解决方法

2022-10-20,,,,

使用java来执行bat命令,如果bat操作时间过长,有可能导致阻塞问题,而且不会执行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产生的错误流及输出流
 */ 
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,就不会阻塞了。

《java执行bat命令碰到的阻塞问题的解决方法.doc》

下载本文的Word格式文档,以方便收藏与打印。