http://blog.csdn.net/arkblue/article/details/7897396
一、直接调用版
使用到Process和Runtime两个类,返回值通过Process类的getInputStream()方法获取
调用shell脚本,判断是否正常执行,如果正常结束,Process的waitFor()方法返回0
二、异步版
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;
public class ShellExec {
public static void execShell(String command) {
InputStreamReader stdISR = null;
InputStreamReader errISR = null;
Process process = null;
// String command = "/home/Lance/workspace/someTest/testbash.sh";
long timeout = 10 * 1000;
try {
process = Runtime.getRuntime().exec(command);
// CommandStreamGobbler errorGobbler = new CommandStreamGobbler(
// process.getErrorStream(), command, "ERR");
// CommandStreamGobbler outputGobbler = new CommandStreamGobbler(
// process.getInputStream(), command, "STD");
// errorGobbler.start();
// 必须先等待错误输出ready再建立标准输出
// while (!errorGobbler.isReady()) {
// Thread.sleep(10);
// }
// outputGobbler.start();
// while (!outputGobbler.isReady()) {
// Thread.sleep(10);
// }
CommandWaitForThread commandThread = new CommandWaitForThread(
process);
commandThread.start();
long commandTime = new Date().getTime();
long nowTime = new Date().getTime();
boolean timeoutFlag = false;
while (!commandThread.isFinish()) {
if (nowTime - commandTime > timeout) {
timeoutFlag = true;
break;
} else {
Thread.sleep(1000);
nowTime = new Date().getTime();
}
}
if (timeoutFlag) {
// 命令超时
// errorGobbler.setTimeout(1);
// outputGobbler.setTimeout(1);
System.out.println("正式执行命令:" + command + "超时");
}
// while (true) {
// if (errorGobbler.isReadFinish() && outputGobbler.isReadFinish()) {
// break;
// }
// Thread.sleep(10);
// }
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
if (process != null) {
process.destroy();
}
}
}
public class CommandWaitForThread extends Thread {
private Process process;
private boolean finish = false;
private int exitValue = -1;
public CommandWaitForThread(Process process) {
this.process = process;
}
public void run() {
try {
this.exitValue = process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
finish = true;
}
}
public boolean isFinish() {
return finish;
}
public void setFinish(boolean finish) {
this.finish = finish;
}
public int getExitValue() {
return exitValue;
}
}