java进程生成器无法获得输出

时间:2014-12-28 06:16:16

标签: java

我想使用java process builder实时获取bat文件输出。但问题是我没有得到任何输出。我可以改进这个以获得输出

这是我的javacode

void pingIp() throws InterruptedException, IOException {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String[] commands = {"C:\\Users\\Madhawa.se\\Desktop\\addonapp\\matrix.bat"};

                ProcessBuilder process = new ProcessBuilder(commands);
                process.redirectErrorStream(true);

                Process shell = process.inheritIO().start();

                //shell.waitFor();
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(shell.getInputStream()));
                BufferedReader stdError = new BufferedReader(new InputStreamReader(shell.getErrorStream()));

                // read the output from the command
                System.out.println("Here is the standard output of the command:\n");
                while ((s = stdInput.readLine()) != null) {
                    System.out.println(":" + s);
                }

                // read any errors from the attempted command
                System.out.println("Here is the standard error of the command (if any):\n");
                while ((s = stdError.readLine()) != null) {
                    System.out.println(":" + s);
                }
            } catch (IOException ex) {
                Logger.getLogger(pingIo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    t.start();

}

我的实际bat文件很复杂所以例如我使用下面的bat文件。这个bat文件以间隔[1 s]打印随机数。所以我想在我的java控制台实时输出

::matrix interval //matrix.bat
@echo off
color 0a
:top
echo %random%%random%%random%%random%
ping 1.1.1.1 -n 1 -w 1000 > nul
goto top

谢谢!

1 个答案:

答案 0 :(得分:2)

inheritIO需要在未通过常规方式读取输出的地方使用。如果使用不当,可能会阻止从过程中读取输出。

您还应该在单独的线程中读取输出/错误流,并在启动这些线程后使用waitFor。这允许您在代码中的那一点阻塞,但仍然处理流,因为如果未读取输出缓冲区,某些进程可能会停止

相关问题