服用下面的範例, 完成在 java 存取外部指令:
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("bash", "-c", "ls /tmp/my-folder-root/");
try {
Process process = processBuilder.start();
StringBuilder output_string = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output_string.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Success!");
System.out.println(output_string);
} else {
//abnormal...
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
執行結果:
說明: 先在 terminal 裡建立資料夾名稱hello-max, 在 eclipse 的 tomcat 的 console 裡可以看到程式輸出的字串, 與實際在檔案系統中的資料夾.