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上有一个关于此技术的很好的示例。