簡體   English   中英

如何在Java 9中獲取Process的commandLine和參數

[英]How to get commandLine & arguments of Process in Java 9

Java 9提供了獲取Process信息的漂亮方法,但我仍然不知道如何獲取該進程的CommandLinearguments

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

結果:

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

但我期待:

Arguments : 1
Command : C:\Windows\System32\notepad.exe
CommandLine : C:\Windows\System32\notepad.exe E:\\test.txt

似乎這是在JDK-8176725中報道的。 以下是描述該問題的評論:

對於其他進程,命令行參數不能通過非特權API使用,因此Optional始終為空。 API明確指出值是特定於操作系統的。 如果將來可以通過Window API獲得參數,則可以更新實現。

順便說一句,信息結構由本機代碼填充; 字段的分配不會出現在Java代碼中。

嘗試使用ProcessBuilder而不是Runtime#exec()

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

或者另一種創建流程的方法:

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

JDK-8176725表示尚未為Windows實現此功能。 這是一個簡單但緩慢的解決方法:

  /**
   * Returns the full command-line of the process.
   * <p>
   * This is a workaround for
   * <a href="https://stackoverflow.com/a/46768046/14731">https://stackoverflow.com/a/46768046/14731</a>
   *
   * @param processHandle a process handle
   * @return the command-line of the process
   * @throws UncheckedIOException if an I/O error occurs
   */
  private Optional<String> getCommandLine(ProcessHandle processHandle) throws UncheckedIOException {
    if (!isWindows) {
      return processHandle.info().commandLine();
    }
    long desiredProcessid = processHandle.pid();
    try {
      Process process = new ProcessBuilder("wmic", "process", "where", "ProcessID=" + desiredProcessid, "get",
        "commandline", "/format:list").
        redirectErrorStream(true).
        start();
      try (InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream());
           BufferedReader reader = new BufferedReader(inputStreamReader)) {
        while (true) {
          String line = reader.readLine();
          if (line == null) {
            return Optional.empty();
          }
          if (!line.startsWith("CommandLine=")) {
            continue;
          }
          return Optional.of(line.substring("CommandLine=".length()));
        }
      }
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM