WebObjects/Web 應用/開發/呼叫命令列應用程式
外觀
這裡,“cat”和“outputCat”是除錯輸出類別
Process process=null;
try {
process = Runtime.getRuntime().exec(commandLine);
OutputStream output = process.getOutputStream();
output.write(inputString.getBytes());
output.close();
process.waitFor();
DataInputStream dis=new DataInputStream(process.getInputStream());
String output;
do {
output = dis.readLine();
if (output != null)
outputCat.debug(output);
} while (output != null);
dis.close();
} catch (IOException e) {
cat.error("IOException: " + e.toString());
} catch (InterruptedException e) {
cat.error("Interrupted process: " + e.toString());
} finally {
if (process != null)
process.destroy();
outputCat.debug("Process finished.");
}
注意:許多人報告了在 Windows 上使用 process.waitFor() 遇到的問題。Omnigroup 的 WebObjects 開發列表中包含許多人針對此問題的解決方法程式碼。
注意 2:此處給出的過程當然是從您的 Java 程式中呼叫命令列中任何可執行檔案,而不僅僅是 Perl 指令碼。
process.waitFor() 不僅僅是 Windows 上的一個問題。這段程式碼確實會導致問題。Process 為 stdout 和 stderr 保持緩衝區。如果您不使用這些流,將會遇到死鎖。使用 Runtime.exec 的正確方法是為 stderr 設定一個執行緒,為 stdout 設定一個執行緒,並自行將它們消費到您自己的緩衝區中,該緩衝區沒有與庫存 VM 相同的限制。
在JavaWorld上有一個關於此技術的很好的示例。