Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a .BAT file in JAVA without opening a command prompt

Tags:

java

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!

like image 362
Simon T Avatar asked Apr 29 '26 16:04

Simon T


2 Answers

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
like image 146
MadProgrammer Avatar answered May 01 '26 06:05

MadProgrammer


A little late but for others who want to try I found the /B of start command.

String[] command = { "cmd", "/C", "start", "/B", "test.bat" };
File path = new File("C:/Users/Me/Desktop/dir/");
Runtime.getRuntime().exec(command, null, path);
like image 23
John Avatar answered May 01 '26 06:05

John