如何使用 Runtime.exec() 或 ProcessBuilder 通过其路径名打开 google chrome?

How can I use either Runtime.exec() or ProcessBuilder to open google chrome through its pathname?

我正在编写一个 java 代码,目的是使用 Google Chrome 在 youtube 上打开 URL,但我未能成功理解这两种方法。这是我目前的尝试。

import java.lang.ProcessBuilder;
import java.util.ArrayList;
public class processTest
{
    public static void main(String[] args)
    {
    ArrayList<String> commands = new ArrayList<>();
    commands.add("cd C:/Program Files/Google/Chrome/Application");
    commands.add("chrome.exe youtube.com");
    ProcessBuilder executeCommands = new ProcessBuilder( "C:/WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe", "cd C:/Program Files/Google/Chrome/Application", "chrome.exe youtube.com");
    }
}

它编译正常,但是当我 运行 它时没有任何反应。怎么回事?

您应该调用 start 方法来执行操作,如下所示:

ProcessBuilder executeCommands = new ProcessBuilder( "C:/WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe", "cd C:/Program Files/Google/Chrome/Application", "chrome.exe youtube.com");
executeCommands.start();

正如 Jim Garrison 所说,ProcessBuilder 的构造函数只执行一个命令。而且您无需浏览目录即可到达可执行文件。

针对您的问题的两种可能解决方案(对我的 Windows 7 有效,如果需要,请务必替换您的 Chrome 路径)

ProcessBuilder一起使用带有两个参数的构造函数:命令、参数(将传递给命令)

    try {
        ProcessBuilder pb =
           new ProcessBuilder(
              "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", 
              "youtube.com");

        pb.start();

        System.out.println("Google Chrome launched!");
    } catch (IOException e) {
        e.printStackTrace();
    }

With Runtime 使用方法 exec 和一个参数,一个 String 数组。第一个元素是命令,以下元素用作此类命令的参数。

    try {
        Runtime.getRuntime().exec(
          new String[]{"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", 
                       "youtube.com"});

        System.out.println("Google Chrome launched!");
    } catch (Exception e) {
        e.printStackTrace();
    }