gpt4 book ai didi

java - 运行时立即获取系统输出(更新 ProgressBar)Java

转载 作者:行者123 更新时间:2023-11-29 03:36:28 25 4
gpt4 key购买 nike

我正在通过 runtime.exec 运行命令,这需要一些时间。我想在那个时候更新我的 ProgressBar。
我已经得到了我想要的系统输出,问题是:我在进程完成时立即得到它。而不是一步一步地更新我的 ProgressBar ...

代码如下

public Runtime rt = Runtime.getRuntime();
public Process pp;

public doit() {
try {
pp = rt.exec(a_long_timed_process);
InputStream is = pp.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if (line.contains("In:")) {
int a = line.indexOf("In:"); //get a string
int b = line.lastIndexOf("%"); //between
String lineout = line.substring(a + 3, b);//"0.00" and "99.99"
double nr = Double.parseDouble(lineout); //make it a double
int round = (int) nr; //make it a usable int
System.out.println(round);
myProgressBar.setValue(round); //UPDATE Progressbar
}
}
pp.waitFor();
} catch (IOException ex) {
Logger.getLogger(Sox.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(Sox.class.getName()).log(Level.SEVERE, null, ex);
}
}

感谢您的帮助
提前致谢

最佳答案

如果您希望能够并发处理其输出,则必须在不同的线程中运行该进程。一个好方法是使用 ProcessBuilder .

来自文档:

This class is used to create operating system processes.

[...]

Starting a new process which uses the default working directory and environment is easy:

Process p = new ProcessBuilder("myCommand", "myArg").start();

Here is an example that starts a process with a modified working directory and environment, and redirects standard output and error to be appended to a log file:

ProcessBuilder pb =
new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
File log = new File("log");
pb.redirectErrorStream(true);
pb.redirectOutput(Redirect.appendTo(log));
Process p = pb.start();
assert pb.redirectInput() == Redirect.PIPE;
assert pb.redirectOutput().file() == log;
assert p.getInputStream().read() == -1;

另见 here另一个代码示例,您可以根据自己的需要进行调整。

关于java - 运行时立即获取系统输出(更新 ProgressBar)Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15282812/

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