简体   繁体   English

从流程的输出流中读取行时,扫描仪未断开

[英]Scanner not breaking when reading a line from a Process' output stream

I am making a program that runs multiple processes, and one of them is a Java program. 我正在制作一个运行多个进程的程序,其中一个是Java程序。

Just say I have a java program that looks like this in a file Foo 只是说我在文件Foo中有一个看起来像这样的Java程序

System.out.println("Hello World!");

And then I have the program 然后我有程序

Process p = Runtime.getRuntime().exec("java Foo");
Scanner scan = new Scanner(p.getInputStream());
while(scan.hasNextLine()) System.out.println(scan.nextLine());
System.out.println("done");
scan.close();

When I run it, it just prints done , and not the Hello World! 当我运行它时,它只是打印done ,而不是Hello World! that should be read from the Process. 应该从流程中读取。 How would I do this? 我该怎么做?

You need to either also handle the process' error stream, or simply redirect that to the stream you're already reading via the ProcessBuilder API. 您还需要处理流程的错误流,或者只是通过ProcessBuilder API将其重定向到您正在读取的流。

ProcessBuilder builder = new ProcessBuilder();
builder.redirectErrorStream(true);
builder.command("java Foo");
Process p = builder.start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM