在項目中執行一個linux的shell腳本,於是需要在java環境下執行外部命令如系統命令、linux命令的需求,本人小小研究了一下,又上網查了一些資料先整理如下。
java執行外部命令主要依賴兩個類Process和Runtime。
一、Process類
ProcessBuilder.start()創建一個本機進程,並返回一個Process子類的一個實例,該實例可以獲取進程的相關信息,也可以控制進程。這個進程沒有自己的終端,它的操作結果io都重定向到了它的父進程,父進程通過getInputStream(),getOutputStream(),getErrorStream()為子進程提供輸入和獲取輸出,而對於io流如果有緩沖大小限制,則可能出現阻塞,導致死鎖情況。
可使用destory()方式強制殺掉子進程,exitValue()返回執行結果,如果子進程需要等待返回,調用waitFor()方法將當前線程等待,直到子進程退出。
二、Runtime類
Runtime.getRuntime().exec() 獲得的就是Process類,exec()方法有多個重載可以使用,針對不同的情況設置不同的參數。另外需要注意的是執行的windows和linux的明林的寫法是不同的。
public class runtimeTest {
String command = "notepad.exe txt.txt";
try {
Process process = Runtime.getRuntime().exec(command);
BufferedInputStream bis = new BufferedInputStream(
process.getInputStream());
BufferedReader br = new BufferedReader( new InputStreamReader(bis));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
if (process.exitValue() != 0) {
System.out.println("error!");
}
bis.close();
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
三、Apache Common-Exec
強烈建議使用apache的第三方庫,該庫提供了更加詳細的設置和監控方法等等。
執行的命令被稱為CommandLine,可使用該類的addArgument()方法為其添加參數,parse()方法將你提供的命令包裝好一個可執行的命令。命令是由執行器Executor類來執行的,DefaultExecutor類的execute()方法執行命令,exitValue也可以通過該方法返回接收。設置ExecuteWatchdog可指定進程在出錯后多長時間結束,這樣有效防止了run-away的進程。此外common-exec還支持異步執行,Executor通過設置一個ExecuteResultHandler類,該類的實例會接收住錯誤異常和退出代碼。
CommandLine cmdLine = new CommandLine("AcroRd32.exe");
cmdLine.addArgument("/h");
cmdLine.addArgument("${file}");
HashMap map = new HashMap();
map.put("file", new File("invoice.pdf"));
commandLine.setSubstitutionMap(map);
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
ExecuteWatchdog watchdog = new ExecuteWatchdog(60*1000);
Executor executor = new DefaultExecutor();
executor.setExitValue(1);
executor.setWatchdog(watchdog);
executor.execute(cmdLine, resultHandler);
// some time later the result handler callback was invoked so we
// can safely request the exit value
int exitValue = resultHandler.waitFor();
以上是自己從common-exec官方文檔自己的理解,如有錯誤望輕拍!