Get output from BAT file using Java
Asked Answered
W

3

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.

Whitening answered 12/6, 2013 at 8:47 Comment(1)
Read (and implement) all the recommendations of When Runtime.exec() won't. 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.Kestrel
A
6

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.

Alchemy answered 12/6, 2013 at 9:21 Comment(2)
this solved it i have another problem which the bat file contains start run.bat command and i need the other result too :(Whitening
You can use CALL to run an other batch files inside your primary script. See link and link for references.Windage
P
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);
}
Parentage answered 12/6, 2013 at 8:49 Comment(2)
dude i tried this didn't work I'm getting null value instead of command resultWhitening
in the ProcessBuilder there is no .redirectInput(); method any suggestion? i use NetBeans BTWWhitening
C
-1
BufferedReader stdInput = new BufferedReader(new 
 InputStreamReader( pr.getErrorStream() ));

instead use

BufferedReader stdInput = new BufferedReader(new 
 InputStreamReader( pr.getInputStream ));
Colorant answered 12/6, 2013 at 8:56 Comment(3)
Don't ignore the error stream. For robust code, both must be consumed.Kestrel
for both while loop required separatelyColorant
This doesn't actually answer the question.Heeled

© 2022 - 2024 — McMap. All rights reserved.