Home > Net >  Java Process Class: Why command "java -version" does not produce outputstream while comman
Java Process Class: Why command "java -version" does not produce outputstream while comman

Time:08-28

Below program:


public class ProcessExample {

    public static void main(String[] args) throws IOException {

        Process process1 = new ProcessBuilder("/bin/ls", "-l").directory(Path.of("/home/yapkm01").toFile()).start();
        System.out.println("ls command:");
        try (var in = new Scanner(process1.getInputStream())) {
            while (in.hasNextLine()) {
                System.out.println(in.nextLine());
            }
        }

        Process process2 = new ProcessBuilder("/bin/java", "-version").start();
        System.out.println("java command:");
        try (var in = new Scanner(process2.getInputStream())) {
            while (in.hasNextLine()) {
                System.out.println(in.nextLine());
            }
        }

    }

}

Output:

ls command:
total 424
drwxr-xr-x  2 yapkm01 yapkm01   4096 Dec 27  2021 Desktop
drwxr-xr-x  2 yapkm01 yapkm01   4096 Apr 30 01:09 Documents
drwxr-xr-x  2 yapkm01 yapkm01   4096 Jul  1 12:06 Downloads
-rw-r--r--  1 yapkm01 yapkm01   8980 Aug  3  2018 examples.desktop
java command:

Notice there is not output for process2 which is java -version. Of course when do i it manually i get below.

yapkm01-/home/yapkm01):-$ java -version
openjdk version "11.0.16" 2022-07-19
OpenJDK Runtime Environment (build 11.0.16 8-post-Ubuntu-0ubuntu122.04)
OpenJDK 64-Bit Server VM (build 11.0.16 8-post-Ubuntu-0ubuntu122.04, mixed mode, sharing)
(yapkm01-/home/yapkm01):-$

Question: Why there is no output for java -version?

CodePudding user response:

$ java --help | grep version
    -version      print product version to the error stream and exit
    --version     print product version to the output stream and exit
    -showversion  print product version to the error stream and continue
    --show-version
                  print product version to the output stream and continue

As you can see, java -version prints to stderr so obviously you won't see the output in stdout. You need to use java --version or capture stderr

CodePudding user response:

"/bin/java" is not the correct PATH to java. Try which java to get the correct path, and use that instead. Also, I suggest you use inheritIO with your ProcessBuilder. Change

Process process2 = new ProcessBuilder("/bin/java", "-version").start();

to

Process process2 = new ProcessBuilder("CORRECT_PATH/java",
        "-version").inheritIO().start();
  • Related