Get output from BAT file using Java

半腔热情 提交于 2020-01-03 11:27:05

问题


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:

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.


回答1:


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

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.




回答2:


You need to start a new thread that would read terminal output stream and copy it to the console, after you call 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 ProcessBuilder class, and try writing something like:

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

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



回答3:


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

instead use

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


来源:https://stackoverflow.com/questions/17061268/get-output-from-bat-file-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!