gpt4 book ai didi

java进程构建器无法获取输出

转载 作者:行者123 更新时间:2023-12-02 05:07:18 25 4
gpt4 key购买 nike

我想使用java进程构建器实时获取bat文件输出。但问题是我没有得到任何输出。我如何改进它以获得输出

这是我的java代码

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秒]打印随机数。所以我想在我的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

谢谢!

最佳答案

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

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

关于java进程构建器无法获取输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27674127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com