Java运行系统命令 (四)

2014-11-24 11:27:41 · 作者: · 浏览: 15
buffer.append(line);
}
result.setOutput(buffer.toString());
}
return result;
}

try {
isFinished = true;
process.exitValue();
} catch (IllegalThreadStateException e) {
// process hasn't finished yet
isFinished = false;
Thread.sleep(INTERVAL);
}
}

} finally {
if (errorStreamReader != null) {
try {
errorStreamReader.close();
} catch (IOException e) {
}
}

if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
}
}
}
}
}

package command;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
* Describe class Command here.
*
*/
public class Command {

private long startTime;
private long timeout;
private static final long INTERVAL = 500;

/*
* command is one system command represented by string
* timeout is milliseconds for waiting the command execution
* throw CommandError if the system command can't be executed
* return CommandResult when the system command is executed no matter what the command returns(succeed or failed)
*/
public CommandResult exec(final String command, long timeout) throws CommandError {
this.timeout = timeout;
try {
Process process = Runtime.getRuntime().exec(command);
CommandResult result = wait(process);
if (process != null) {
process.destroy();
}
return result;
} catch (Exception ex) {
throw new CommandError(ex);
}
}

private boolean isTimeout() {
return System.currentTimeMillis() - startTime >= timeout;
}

private CommandResult wait(final Process process) throws InterruptedException, IOException {
BufferedReader errorStreamReader = null;
BufferedReader inputStreamReader = null;
try {
errorStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
inputStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

//timeout control
startTime = System.currentTimeMillis();
boolean isFinished = false;

for (;;) {
if (isTimeout()) {
CommandResult result = new CommandResult();
result.setExitValue(CommandResult.EXIT_VALUE_TIMEOUT);
result.setOutput("Command process timeout");
return result;
}

if (isFinished) {
CommandResult result = new CommandResult();
result.setExitValue(process.waitFor());

//parse error info
if (errorStreamReader.ready()) {
StringBuilder buffer = new StringBuilder();
String line;