這是我的代碼,通過Java在Windows中啓動一個進程(併吞噬輸出)。runtime.exec立即發送EOF輸入?
public static void main(String[] args) throws Exception {
String[] command = new String[3];
command[0] = "cmd";
command[1] = "/C";
command[2] = "test.exe";
final Process child = Runtime.getRuntime().exec(command);
new StreamGobbler(child.getInputStream(), "out").start();
new StreamGobbler(child.getErrorStream(), "err").start();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
child.getOutputStream()));
out.write("exit\r\n");
out.flush();
child.waitFor();
}
private static class StreamGobbler extends Thread {
private final InputStream inputStream;
private final String name;
public StreamGobbler(InputStream inputStream, String name) {
this.inputStream = inputStream;
this.name = name;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
inputStream));
for (String s = in.readLine(); s != null; s = in.readLine()) {
System.out.println(name + ": " + s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
不知何故在問題(處理)程序(在右作爲後餘步驟PAS的「EXEC」線)recieving一個EOF馬上並且因此運行時間之後立即發出一個錯誤(檢測到的,無效的)消息。 exec被調用。我可以通過命令提示符手動運行此程序,而不會出現此問題,但已經確認在Windows上發送ctrl-z是導致此消息的原因。
任何人都知道這可能是導致此?
如果很重要,我已經嘗試直接運行該過程作爲「test.exe」而不是cmd/c test.exe,但是當我這樣做時,我看不到輸出通過inputStream。而當我沒有/ c做cmd test.exe時,沒有任何區別。
謝謝吉姆,那正是我需要的。它確實看起來像程序沒有像sort或其他cmd行實用程序那樣處理stdin。 – user1309154 2012-04-04 13:26:06