时间:2021-05-19
使用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,就不会阻塞了。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
Linux执行.sh文件,提示Nosuchfileordirectory的问题问题描述解决方法分析原因,可能因为我平台迁移碰到权限问题我们来进行权限转换1)在W
本文实例讲述了PHP编程中的Session阻塞问题与解决方法。分享给大家供大家参考,具体如下:使用session过程中,在开启session后,同一浏览器,执行
问题描述:itunes磁盘已满 解决方法:Junction是一个命令行工具,需要在cmd窗口执行。方法如下(以win7为例): 1.下载Junction
下面VPS侦探说一下几个解决方法:MySQL数据库导出方法1:mysqldump命令执行命令:/usr/local/mysql/bin/mysqldump-u用
本文实例讲述了Java基于Runtime调用外部程序出现阻塞的解决方法,是一个很实用的技巧。分享给大家供大家参考。具体分析如下:有时候在java代码中会调用一些