Archit Arora
Archit Arora

Reputation: 2636

Not able to run cmd command through java

I have a .bat file called galen.bat. I included the path to this file in the PATH environment variable.

When I run:

galen.bat --version

in cmd, I get the following output:

Galen Framework
Version: 1.6.3
JavaScript executor: Rhino 1.7 release 5 2015 01 29

I have the following java code through which I'm trying to run the same command through my application -

 public static void main(String[] args) throws Exception {
            ProcessBuilder builder = new ProcessBuilder(
                "cmd.exe", "/c", "galen.bat --version");
            builder.redirectErrorStream(true);
            Process p = builder.start();
            BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while (true) {
                line = r.readLine();
                if (line == null) { break; }
                System.out.println(line);
            }
        }

When I run this I get the following error -

'galen.bat' is not recognized as an internal or external command,
operable program or batch file.

Please note that if I use

ProcessBuilder builder = new ProcessBuilder(
                    "cmd.exe", "/c", "java -version");

instead of

ProcessBuilder builder = new ProcessBuilder(
                    "cmd.exe", "/c", "galen.bat --version");

then I do get the correct output in my eclipse console window -

java version "1.7.0_03"
Java(TM) SE Runtime Environment (build 1.7.0_03-b05)
Java HotSpot(TM) 64-Bit Server VM (build 22.1-b02, mixed mode)

Why is galen.bat --version not working? How do I fix this? Thanks!

Upvotes: 1

Views: 897

Answers (1)

Jordi Castilla
Jordi Castilla

Reputation: 27003

According the docs:

When a Java application uses a ProcessBuilder object to create a new process, the default set of environment variables passed to the new process is the same set provided to the application's virtual machine process. The application can change this set using ProcessBuilder.environment.

So you must include the new path of galen.bat in the path of your JVM or change ProcessBuilder.environment to your system PATH, but according this answer, seems last option is not possible.

Upvotes: 1

Related Questions