![](/img/trans.png)
[英]“Cannot run program” when using Runtime.exec with spaces in command
[英]“Cannot run program” when using Runtime.exec with spaces in program filename
我正在使用以下代码打开“sample.html”文件。
String filename = "C:/sample.html";
String browser = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe";
Runtime rTime = Runtime.getRuntime();
Process pc = rTime.exec(browser + filename);
pc.waitFor();
但是,我收到以下错误。
java.io.IOException: Cannot run program "C:/Program": CreateProcess error=2, The system cannot find the file specified
有人可以帮我解决这个问题。 提前致谢。
Runtime.exec(String)
自动在空格处拆分字符串,假设第一个标记是命令名称,其余是命令行参数。 此外,您在browser
和file
之间没有空格,尽管这不是问题的根本原因。
它认为你想用两个命令行参数运行“C:/Program”:
改用Runtime.exec(String[])
,这样你就可以完全控制什么是什么:
String[] command = new String[]{browser, filename};
Runtime.exec(command);
尝试这个。
String filename = "C:\\sample.html";
String browser = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(new String[] {browser, filename});
} catch (IOException e) {
e.printStackTrace();
}
停止使用Runtime.exec(String)
- 问题在于它如何处理单个字符串输入。
错误消息指示失败的方式/位置:请注意,它在“C:/Program”(或第一个空格)之后停止。 这表明 exec “错误地”解析了字符串,因此甚至没有寻找正确的可执行文件。
无法运行程序“C:/Program”
相反,请考虑使用ProcessBuilder 。 虽然用法仍然依赖于系统,但 ProcessBuilder 允许将可执行文件名(并且需要专门处理它)和参数分开,并且正确调用目标是最好的。
String filename = "C:\\sample.html";
String browser = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
ProcessBuilder pb = new ProcessBuilder(browser, filename);
// setup other options ..
// .. and run
Process p = pb.start();
p.waitFor();
据我所知,在 Windows 中,ProcessBuilder 会将各个组件用引号括起来; 当参数包含引号时,这可能会产生不同的问题..
参数必须单独传递:
Process pc = rTime.exec(new String[]{browser, filename});
使用exec()
与使用命令行不同 - 您不能使用空格将命令与其参数分隔开。 您的尝试会尝试执行一个命令,其路径是 exec 和文件名的串联,作为一个巨大的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.