How to get command line and process arguments in Java 9

Java 9 has proven that you can get information about Process , but I still don't know how to get CommandLine and process arguments :

 Process p = Runtime.getRuntime().exec("notepad.exe E:\\test.txt"); ProcessHandle.Info info = p.toHandle().info(); String[] arguments = info.arguments().orElse(new String[]{}); System.out.println("Arguments : " + arguments.length); System.out.println("Command : " + info.command().orElse("")); System.out.println("CommandLine : " + info.commandLine().orElse("")); 

Result:

 Arguments : 0 Command : C:\Windows\System32\notepad.exe CommandLine : 

But I expect:

 Arguments : 1 Command : C:\Windows\System32\notepad.exe CommandLine : C:\Windows\System32\notepad.exe E:\\test.txt 
+7
java windows process java-9
source share
2 answers

This seems to have been reported in JDK-8176725 . Here is a comment describing the problem:

Command line arguments are not accessible through an unprivileged API for other processes and therefore the option is always empty. The API is explicit that the values ​​are OS specific. If arguments are available in the Window API in the future, the implementation may be updated.

BTW, the information structure is populated with its own code; field assignments are not displayed in Java code.

+6
source share

Try using ProcessBuilder instead of Runtime#exec()

 Process p = new ProcessBuilder("notepad.exe", "E:\\test.txt").start(); 

Or another way to create a process:

 Process p = Runtime.getRuntime().exec(new String[] {"notepad.exe", "E:\\test.txt"}); 
+1
source share

All Articles