Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中重定向子进程的I/O(为什么&x27;t ProcessBuilder.inheritIO()不起作用?)_Java_Process_Io - Fatal编程技术网

在Java中重定向子进程的I/O(为什么&x27;t ProcessBuilder.inheritIO()不起作用?)

在Java中重定向子进程的I/O(为什么&x27;t ProcessBuilder.inheritIO()不起作用?),java,process,io,Java,Process,Io,我将以以下方式启动一个流程 try { final Process mvnProcess = new ProcessBuilder("cmd", "/c", "mvn", "--version") .directory(new File(System.getProperty("user.dir"))) .inheritIO() .start(); System.exit(mvnProcess.waitFor(

我将以以下方式启动一个流程

try {
    final Process mvnProcess = new ProcessBuilder("cmd", "/c", "mvn", "--version")
            .directory(new File(System.getProperty("user.dir")))
            .inheritIO()
            .start();
    System.exit(mvnProcess.waitFor());
} catch (final IOException ex) {
    System.err.format(IO_EXCEPTION);
    System.exit(1);
} catch (final InterruptedException ex) {
    System.err.format(INTERRUPTED_EXCEPTION);
    System.exit(1);
}
因为我调用了
inheritaio()
,所以我希望子进程的输出出现在控制台上,但什么也没有出现。我错过了什么


Edit:我知道我可以使用
mvnProcess.getInputStream()
显式读取进程的输出,并将其以循环方式写入控制台(或任何地方)。但是我不喜欢这个解决方案,因为循环会阻塞我的线程
inheritaio()
看起来很有希望,但显然我不明白它是如何工作的。我希望这里有人能对此有所了解。

也许可以选择从子流程中读取:

将此代码添加到
start()
之后,即可将其打印到标准输出:

    InputStream is = mvnProcess.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ((line = br.readLine()) != null)
    {
        System.out.println(line);
    }

您可以使用.redirectError(Redirect.INHERIT)。
它将子进程标准I/O的源和目标设置为与当前Java进程的源和目标相同。

如果在cmd.exe中执行
mvn--version>somefile.txt
?@ARRG我得到一个名为somefile.txt的文件,其中包含maven的版本信息1)读取(并实现)所有建议。这可能会解决问题。如果没有,它应该提供更多关于失败原因的信息。然后忽略它引用的
exec
,并(继续)使用
ProcessBuilder
构建
流程。2) 将形式为
catch(Exception e){..
的代码更改为
catch(Exception e){e.printStackTrace();//信息量很大!
@andrewhompson 1)我读了整篇文章,但恐怕没有帮助。我的问题是
inheritaio()
不起作用(在我的情况下).2)我没有遇到任何异常,因此这就离题了。对不起……你做到了吗?:/是的,我知道。它可以工作(+1)。但是,只有当我省略
inheritaio()
,它才能工作。我希望找到如何使
inheritaio()
工作并摆脱while循环,因为它阻塞了我的线程。