使用 Java 从 BAT 文件中获取输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17061268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:51:21  来源:igfitidea点击:

Get output from BAT file using Java

javanetworkingwindows-7processruntime.exec

提问by Muath

I'm trying to run a .bat file and get the output. I can run it but I can't get the results in Java:

我正在尝试运行 .bat 文件并获取输出。我可以运行它,但我无法在 Java 中获得结果:

String cmd = "cmd /c start C:\workspace\temp.bat";

Runtime r = Runtime.getRuntime();
Process pr = r.exec(cmd);

BufferedReader stdInput = new BufferedReader(
    new InputStreamReader( pr.getInputStream() ));

String s ;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

The result is null. No idea why I get this. Note that I'm using Windows 7.

结果是null。不知道为什么我会得到这个。请注意,我使用的是 Windows 7。

采纳答案by Rapha?l

Using "cmd /c start [...]" to run a batch file will create a sub process instead of running your batch file directly.

使用“cmd /c start [...]”运行批处理文件将创建一个子进程,而不是直接运行批处理文件。

Thus, you won't have access to its output. To make it work, you should use:

因此,您将无法访问其输出。要使其工作,您应该使用:

String cmd = "C:\workspace\temp.bat";

It works under Windows XP.

它在 Windows XP 下工作。

回答by Juned Ahsan

You need to start a new thread that would read terminal output stream and copy it to the console, after you call process.waitFor().

您需要启动一个新线程,在您调用process.waitFor().

Do something like:

做类似的事情:

String line;
Process p = Runtime.getRuntime().exec(...);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
    System.out.println(line);
}
input.close();

Better approach will be to use the ProcessBuilderclass, and try writing something like:

更好的方法是使用ProcessBuilder该类,并尝试编写如下内容:

ProcessBuilder builder = new ProcessBuilder("/bin/bash");
builder.redirectInput();
Process process = builder.start();

while ((line = reader.readLine ()) != null) {
    System.out.println ("Stdout: " + line);
}

回答by shreyansh jogi

BufferedReader stdInput = new BufferedReader(new 
 InputStreamReader( pr.getErrorStream() ));

instead use

而是使用

BufferedReader stdInput = new BufferedReader(new 
 InputStreamReader( pr.getInputStream ));