Java 进程类:为什么命令“java -version”不产生输出流,而命令“ls -l”却产生输出流?

yap*_*m01 0 java java-11

下面的程序:


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());
            }
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

输出:

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:
Run Code Online (Sandbox Code Playgroud)

请注意,process2 没有输出,即 java -version。当然,我什么时候手动进行,我会得到下面的结果。

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):-$
Run Code Online (Sandbox Code Playgroud)

问题:为什么 java -version 没有输出?

phu*_*clv 10

$ 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
Run Code Online (Sandbox Code Playgroud)

如您所见,java -version打印到 stderr,因此显然您不会在 stdout 中看到输出。您需要使用java --version或捕获 stderr