6

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.

Rohan Singh
  • 20,497
  • 1
  • 41
  • 48
Muath
  • 4,351
  • 12
  • 42
  • 69
  • Read (and implement) *all* the recommendations of [When Runtime.exec() won't](http://www.javaworld.com/jw-12-2000/jw-1229-traps.html). That might solve the problem. If not, it should provide more information as to the reason it failed. Then ignore that it refers to `exec` and build the `Process` using a `ProcessBuilder`. Also break a `String arg` into `String[] args` to account for arguments which themselves contain spaces. – Andrew Thompson Jun 12 '13 at 08:59

3 Answers3

5

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.

Rohan Singh
  • 20,497
  • 1
  • 41
  • 48
Raphaël
  • 3,646
  • 27
  • 28
  • this solved it i have another problem which the bat file contains start run.bat command and i need the other result too :( – Muath Jun 12 '13 at 15:16
  • 1
    You can use **CALL** to run an other batch files inside your primary script. See [link](http://www.robvanderwoude.com/call.php) and [link](http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/call.mspx?mfr=true) for references. – Raphaël Jun 12 '13 at 15:41
4

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);
}
Rohan Singh
  • 20,497
  • 1
  • 41
  • 48
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
-1
BufferedReader stdInput = new BufferedReader(new 
 InputStreamReader( pr.getErrorStream() ));

instead use

BufferedReader stdInput = new BufferedReader(new 
 InputStreamReader( pr.getInputStream ));
shreyansh jogi
  • 2,082
  • 12
  • 20