Java进程的输入/输出流
Java进程的输入/输出流
以下是我有关上述代码示例的内容。您可以输入一个命令到bash shell中,例如echo test
,然后将结果回显出来。然而,在第一次读取之后,其他输出流就不起作用了。这是为什么呢?我做错了什么吗?我的最终目标是创建一个多线程定时任务,定期执行一个命令到/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); }