我有下面的代码示例。通过这种方式,您可以向 bash shell 输入一个命令,例如 echo test
,并将结果 echo 回。不过,经过第一次阅读。其他输出流不工作?
为什么会这样,还是我做错了什么?我的最终目标是创建一个 Threaded 调度任务,该任务定期执行/bash 命令,这样 OutputStream
和 InputStream
就必须协同工作,而不能停止工作。我也一直在经历 java.io.IOException: Broken pipe
的错误有什么想法吗?
谢谢。
String line;
Scanner scan = new Scanner(System.in);
Process process = Runtime.getRuntime ().exec ("/bin/bash");
OutputStream stdin = process.getOutputStream ();
InputStream stderr = process.getErrorStream ();
InputStream stdout = process.getInputStream ();
BufferedReader reader = new BufferedReader (new InputStreamReader(stdout));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
String input = scan.nextLine();
input += "\n";
writer.write(input);
writer.flush();
input = scan.nextLine();
input += "\n";
writer.write(input);
writer.flush();
while ((line = reader.readLine ()) != null) {
System.out.println ("Stdout: " + line);
}
input = scan.nextLine();
input += "\n";
writer.write(input);
writer.close();
while ((line = reader.readLine ()) != null) {
System.out.println ("Stdout: " + line);
}