简体   繁体   English

java进程buider无法获得输出

[英]java process buider failed to get output

i want to get bat file output real time using java process builder .but the problem is i'm not getting any output .how can i improve this to get output 我想使用Java process builder实时获取bat文件输出。但是问题是我没有任何输出。我该如何改善它以获取输出

this is my javacode 这是我的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();

}

my actual bat file is complex so for example i use following bat file.this bat file print random numbers in intervals[1 s].so i want to get output in my java console in real time 我的实际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

thanks! 谢谢!

inheritIO needs to be used in places where output is not been read through normal means. 需要在无法通过常规方式读取输出的地方使用inheritIO When used incorrectly it can prevent output from been read from the process. 如果使用不当,可能会阻止从过程中读取输出。

You should also read the output/error streams in a separate thread and use waitFor AFTER you've started those threads. 您还应该在单独的线程中读取输出/错误流,并在启动这些线程之后使用waitFor This allows you to block at that point in the code, but still process the streams, as some processes can stall if the output buffer is not read 这使您可以在代码的这一点上进行阻塞,但仍可以处理流,因为如果未读取输出缓冲区,则某些进程可能会停顿

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

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