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,就不會阻塞了。
相關文章
Spring?Boot自定義?Starter并推送到遠端公服的詳細代碼
這篇文章主要介紹了Spring?Boot自定義?Starter并推送到遠端公服,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-09-09SpringBoot使用AOP實現(xiàn)統(tǒng)一角色權限校驗
這篇文章主要介紹了SpringBoot如何使用AOP實現(xiàn) 統(tǒng)一角色權限校驗,文中有詳細的代碼示例講解和操作流程,具有一定的參考價值,需要的朋友可以參考下2023-07-07Idea進行pull的時候Your local changes would be
這篇文章主要介紹了Idea進行pull的時候Your local changes would be overwritten by merge.具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11SSH框架網(wǎng)上商城項目第7戰(zhàn)之整合Struts2和Json
SSH框架網(wǎng)上商城項目第7戰(zhàn)之整合Struts2和Json,打通EasyUI和Struts2之間的交互,感興趣的小伙伴們可以參考一下2016-05-05