前面寫過一個版本的Java代碼用來調用linux shell腳本,原文如下:http://www.linuxidc.com/Linux/2013-05/83739.htm
不過沒有試過Windows下運行,試了一下,還是不錯的,把代碼做了一些調整,封裝成對象,這樣更方便多線程下調用,不用擔心靜態變量互相干擾的問題。
先看一下怎麼用:
public static void main(String[] args) {
try {
Command command = new Command();
CommandResult result1 = command.exec("net stop nginx", 20000);
System.out.println("command executiion succeeds: " + result1.getOutput());
CommandResult result2 = command.exec("net start nginx", 20000);
System.out.println("command executiion succeeds: " + result2.getOutput());
} catch (CommandError ex) {
System.out.println("command execution failed: " + ex.getMessage());
}
}
由此可見,有三個類:Command, CommandResult和CommandError。
當命令不能運行,將會拋出CommandError異常對象。如果命令能夠運行,不管是否成功或者失敗,都返回CommandResult對象,裡面有兩個屬性output和error,包含了執行成功的消息和錯誤消息。
CommandError.java代碼:
package command;
/**
*
* @author shu6889
*/
public class CommandError extends Exception {
/**
* Creates a new instance of
* <code>CommandError</code> without detail message.
*/
public CommandError() {
}
/**
* Constructs an instance of
* <code>CommandError</code> with the specified detail message.
*
* @param msg the detail message.
*/
public CommandError(String msg) {
super(msg);
}
public CommandError(Throwable ex) {
super(ex);
}
}
CommandResult.java代碼
package command;
/**
* Describe class CommandResult here.
*
*/
public class CommandResult {
public static final int EXIT_VALUE_TIMEOUT=-1;
private String output;
void setOutput(String error) {
output=error;
}
public String getOutput(){
return output;
}
int exitValue;
void setExitValue(int value) {
exitValue=value;
}
int getExitValue(){
return exitValue;
}
private String error;
/**
* @return the error
*/
public String getError() {
return error;
}
/**
* @param error the error to set
*/
public void setError(String error) {
this.error = error;
}
}