![](/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.