问题
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