从 main() 中启动应用程序。一起指定路径和文件名还是单独指定?

Launching an app from within main(). Specify path and filename together or separately?

据我了解,try块中的前两个语句应该具有相同的效果; launch chrome.exe,但是第一个导致IO异常,因为它找不到chrome.exe。我做错了什么吗?

import java.io.File;

public class Program
{
    public static void main( final String[] args )
    {
            try
            {
                //Process process = Runtime.getRuntime().exec("chrome.exe", null, new File("C:\Program Files (x86)\Google\Chrome\Application\"));
                Process process = Runtime.getRuntime().exec("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe");
                process.waitFor();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
    }
}

堆栈跟踪:

java.io.IOException: Cannot run program "chrome.exe" (in directory "C:\Program Files (x86)\Google\Chrome\Application"): CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at java.lang.Runtime.exec(Runtime.java:620)
    at java.lang.Runtime.exec(Runtime.java:450)
    at Program.main(Program.java:16)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
    at java.lang.ProcessImpl.start(ProcessImpl.java:137)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 3 more

在您的第一个示例中,将 "chrome.exe" 更改为 "notepad.exe":

Process process = Runtime.getRuntime().exec("notepad.exe", null, new File("C:\Program Files (x86)\Google\Chrome\Application\"));

您会发现这行得通。这是因为"notepad.exe"所在的目录在你的WindowsPath环境变量中。

问题是用Runtime.exec(String command, String[] envp, File dir)方式执行时,还需要在Path环境变量中有正在执行的可执行文件。所以我继续将 C:\Program Files (x86)\Google\Chrome\Application 添加到我的路径,然后你的代码按预期执行。

我觉得这有点奇怪,只是因为我可以 cdC:\Program Files (x86)\Google\Chrome\Application 并执行 "chrome.exe" 并且它有效。所以这里似乎有一个不一致。在 Windows 的命令提示符中,当我在一个目录(我假设是工作目录)时,我可以在其中执行可执行文件,而无需在 Path env 变量中包含这些可执行文件。但在使用 Runtime.exec(String command, String[] envp, File dir).

时情况并非如此