1

I am new to ProcessBuilder. Today I am writing a simple application to execute the "java -version" but always got the IOException.

ProcessBuilder pb = new ProcessBuilder("java -version");
        try {
            Map<String, String> map = pb.environment();  
            Process p  = pb.start();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

The exception thrown as below

java.io.IOException: Cannot run program "java -version": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)

I can ensure that JAVA_HOME is set in environment variable, my eclipse is pointing to the jdk too.

JAVA_HOME=C:\JDK1.8.0_66-X64.

Can anyone tell what the problem is in my code/settings ?

jm li
  • 303
  • 2
  • 9
  • 18
  • 1
    You need to pass `"java"` and `"-version"` as separate command arguments when you're constructing the `ProcessBuilder` – JonK Dec 13 '16 at 11:08
  • 1
    ProcessBuilder takes the first element of array and interprets it as the program(command) name and rest of all as arguments to the program. Try ProcessBuilder pb = new ProcessBuilder(new String[]{"java", "-version"}); – Shubham Chaurasia Dec 13 '16 at 11:10
  • @ShubhamChaurasia There is a varargs constructor so you don't need to manually create the array – JonK Dec 13 '16 at 11:21
  • @JonK right and sure it is!! Actually I am habitual of firing long commands so used to pass array over there. – Shubham Chaurasia Dec 13 '16 at 11:23

1 Answers1

1

The constructor of the class ProcessBuilder you are using takes an argument of type String.... Also the first element of this must be the name of the operating system program alone. You are getting this exception since the system could not find file named java -version.exe(if you are in Windows). The file name you want is java.exe So use ProcessBuilder("java", "-version"). See the documentation here. There is a nice example in the documentation.

AJA
  • 456
  • 3
  • 12
  • Thx. By splitting the command into two parts the program runs with no exception. But I can't find there is any output by checking the p.getInputStream() right after pb.start(). I am following the approach here [link]http://stackoverflow.com/questions/3936023/printing-runtime-exec-outputstream-to-console – jm li Dec 13 '16 at 13:03
  • I have figured it out . Need to append inheritIO() for pb – jm li Dec 13 '16 at 13:38