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?
2
Answers
As you can see,
java -version
prints to stderr so obviously you won’t see the output in stdout. You need to usejava --version
or capture stderrI think this question is really about learning about running subprocesses, based on the name ‘ProcessExample’.
However, if what you really want is the version of Java your program is running (which is of course not necessarily the same version that an arbitrary "java" command line will use), then