由于某些原因,此代码仅在关闭输出流时才有效。如何在不关闭它的情况下使其工作?
我想保持打开状态,这样我就可以继续向流程发送数据而无需重新启动它。
ProcessBuilder pbuilder = new ProcessBuilder(procCmds);
pbuilder.directory(new File(workingDir));
Process p = pbuilder.start();
BufferedWriter outputStream = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
String str = "hello world heard from java\n";
outputStream.write(str, 0, str.length());
outputStream.flush();
System.out.println("wrote " + str);
BufferedReader errorStream = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader inputStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while((line=errorStream.readLine())!=null)
System.out.println(line);
while((line=inputStream.readLine())!=null)
System.out.println(line);
//p.waitFor();
outputStream.close();
errorStream.close();
inputStream.close();
答案 0 :(得分:1)
您需要合并错误和输入流,或者在单独的线程中读取其中一个。目前您正在尝试将错误流读取到EOS,这只会在进程退出时发生,因此您根本无法读取输入流。在进程退出之前,您不会在输入流上获得EOS,因此,如果您要提供更多输出,则将其读取到EOS并不是很有意义。可能你应该在不同的线程中读取两个流。