Java 如何避免getRuntime.exec()在读取inputStream时阻塞?

Java 如何避免getRuntime.exec()在读取inputStream时阻塞?,java,runtime.exec,Java,Runtime.exec,我在java代码中调用位于jar文件某处的类(使用java-classpath/file.jar classname) 我的问题是,当命令genkoscondmand无效时,调用input.readLine()将阻塞程序。所以我添加了input.ready(),希望避免阻塞。当我调试程序时,一切正常。似乎有效。但是,当不在调试中运行它时,缓冲区永远不会准备好 // Execute a command with an argument that contains a space

我在java代码中调用位于jar文件某处的类(使用java-classpath/file.jar classname)

我的问题是,当命令
genkoscondmand
无效时,调用
input.readLine()
将阻塞程序。所以我添加了
input.ready()
,希望避免阻塞。当我调试程序时,一切正常。似乎有效。但是,当不在调试中运行它时,缓冲区永远不会准备好

        // Execute a command with an argument that contains a space
        String[] genKOSCommand = new String[] {
                "java",
                "-classpath",
                Config.XDSI_TEST_KIT_HOME + "/xdsitest/lib/xdsitest.jar;"
                        + Config.XDSI_TEST_KIT_HOME + "/xdsitest/classes",
                "ca.etsmtl.ihe.xdsitest.docsource.SimplePublisher", "-k",
                "C:/Softmedical/Viewer_Test/xdsi-testkit-2.0.4/xdsihome/usr/data/image14.dcm" };

        Process child = Runtime.getRuntime().exec(genKOSCommand);

        BufferedReader input = new BufferedReader(new InputStreamReader(
                child.getInputStream()), 13107200);

        String line = null;

        if (input.ready()) {
            while ((line = input.readLine()) != null) {
                System.out.println(line);
            }

            try {
                child.waitFor();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
关于如何检测已执行命令的问题,有什么建议吗


谢谢。

您需要在循环中等待BufferedReader准备就绪

while (input.ready() == false) { /* intentional empty space here */ }

while ((line = input.readLine()) != null) {
    System.out.println(line);
}
/* rest of code follows */

这在以前已经被回答过很多次了,规范文章是。正如我在前面的问题中所建议的,您可以使用不同的线程来读取每个流。@MByD因此,如果我启动线程来读取流,这只会避免阻塞我的主进程。但是readLine仍然会阻塞线程,不是吗?(重复)该链接只告诉我使用RTFM,并且每个流都有不同的线程,这还不够。@code gijoe-那么您到底缺少什么?您可以在单独的线程中读取流。在主线程中,等待进程完成。如果它是一个无效命令,它应该很快完成,并从
waitFor()
方法中得到一个非零结果。