Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get output from BAT file using Java

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.

like image 428
Muath Avatar asked Jun 12 '13 08:06

Muath


2 Answers

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.

like image 139
Raphaël Avatar answered Sep 18 '22 12:09

Raphaël


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);
}
like image 27
Juned Ahsan Avatar answered Sep 21 '22 12:09

Juned Ahsan