【问题标题】:How can I use either Runtime.exec() or ProcessBuilder to open google chrome through its pathname?如何使用 Runtime.exec() 或 ProcessBuilder 通过其路径名打开谷歌浏览器?
【发布时间】:2017-03-08 01:18:23
【问题描述】:

我正在编写一个 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");
    }
}

它编译正常,但是当我运行它时没有任何反应。什么交易?

【问题讨论】:

  • 您是否阅读了ProcessBuilder 构造函数的Javadoc?它接受一个单个命令及其参数,而不是一系列命令。

标签: java processbuilder runtime.exec


【解决方案1】:

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

Runtime 使用方法 exec 和一个参数,一个字符串数组。第一个元素是命令,后面的元素用作该命令的参数。

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

【讨论】:

    【解决方案2】:

    你应该调用 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();
    

    【讨论】:

    • 你测试了吗?我已经尝试了您的代码,但没有任何反应。
    猜你喜欢
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    相关资源
    最近更新 更多