Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Process Class: Why command "java -version" does not produce outputstream while command "ls -l" does?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

$ 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading