文中的注释纯属个人理解,有不当的地方勿喷,引用须谨慎!
有一个问题没搞好,当外部脚本引用其他脚本时,脚本中须用绝对路径,否则会将引用的脚本当命令执行,这样会提示 找不到命令,如果有谁知道怎么解决请一定要告诉我,先口头感谢作为酬劳。
import java.lang.Runtime;
import java.lang.Process;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.Exception;
import java.io.*;
public class RunCommand {
/**
* @param args
* @author yinduasan
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
RunCommand javaExec = new RunCommand();
String pig = "D:\\java\\pig.bat";
javaExec.runProcess(pig,5);
// if (args.length >= 1) {
// javaExec.testProcess(args[0]);
// }
// else{
// javaExec.testProcess(null);
// }
}
/**
* @param userInputCmd 执行的命令
* @param tnum 等待时间
* @throws IOException
* @throws InterruptedException
*/
public void runProcess(String userInputCmd,int tnum) throws IOException, InterruptedException {
if (userInputCmd == null) {
throw new NullPointerException("命令为空 ==!");
}
if (!(new File(userInputCmd)).exists()) {
throw new FileNotFoundException("找到不执行文件 ==!") ;
}
long sleepTime = tnum * 1000;
ProcessBuilder builder = new ProcessBuilder();
builder.redirectErrorStream(true); //输入流与错误流都可以用InputStreamReader获取
builder.command(userInputCmd);
Process process = builder.start() ;
// process = Runtime.getRuntime().exec(userInputCmd);
final InputStream ins = process.getInputStream() ;
final StringBuilder sb = new StringBuilder();
new Thread() {
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(ins));
try {
String lineStr = null;
while ((lineStr = br.readLine()) != null) {
if (lineStr != null)
sb.append(lineStr + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} // end try
} // end run
}.start(); // end new Thread
Thread.currentThread().sleep(sleepTime) ;
String excep = sb.toString();
process.getOutputStream().close(); //如果不关闭,有时候会造成IO阻塞,导致进程挂死
if (process.waitFor() != 0) {//超时时间到进程仍没有返回结果, 0 为正常执行结束
if (process.exitValue() != 0) {//外部程序执行结果, 0为正常结束
throw new InterruptedException("执行命令被中断 ");
}else {
process.destroy();
//截取最后输出的内容抛出
// String excep = sb.toString();
// System.out.println(excep);
excep = excep.substring(excep.length() -2000, excep.length()) ;
throw new InterruptedException(excep);
}//end if process.exitValue
}
int exitValue = process.waitFor();
// System.out.println(excep);
// System.out.println(exitValue);
// process.destroy();
}
}
如果找到方法再补充。