I've been trying to run an executable .bat
file in Java using the line:
Runtime.getRuntime().exec("call " + batFile);
But it returns an error
Could not start process with commandLine nullCreateProcess: call batfilename here error=2 IOException: Create Process: call batfilename here error=2
I managed to bypass this by replacing the String
in the exec()
function with "cmd /c start " + batFile
but this opens a command prompt which is not allowed.
Are there workarounds to this? Thanks!
Try running the batch file directly, for example...
ProcessBuilder pb = new ProcessBuilder("C:/Test.bat");
pb.redirectError();
try {
Process p = pb.start();
try (InputStream inputStream = p.getInputStream()) {
int in = -1;
while ((in = inputStream.read()) != -1) {
System.out.print((char)in);
}
}
System.out.println("Exited with " + p.waitFor());
} catch (IOException | InterruptedException ex) {
ex.printStackTrace();
}
This was the batch file...
@echo Hello World
(I know, massive) and the code outputted...
Hello World
Exited with 0
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments