簡體   English   中英

Java - 使用 ProcessBuilder directory() 時系統找不到指定的文件

[英]Java - The system cannot find the file specified when using ProcessBuilder directory()

我正在嘗試在使用 ProcessBuilder 的 directory() 方法時在 Java 中運行一個子進程。 但是,每當我使用 directory() 方法時,程序都會失敗,說找不到文件。 但是,該文件存在於工作目錄中。

Process process = new ProcessBuilder("firefox")
                    .directory(new File("C:\\Program Files\\Mozilla Firefox"))
                    .inheritIO()
                    .start();

Output:

Could not start server due to java.io.IOException: Cannot run program "firefox" (in directory "C:\Program Files\Mozilla Firefox"): CreateProcess error=2, The system cannot find the file specified

當我省略 directory() 方法並創建像這樣的 ProcessBuilder 時: new ProcessBuilder("C:\\Program Files\\Mozilla Firefox\\firefox") ,它工作正常並且 firefox.exe 成功啟動。

這發生在 Windows 和 Linux 上。

我已經嘗試了多個版本的啟動命令(如firefoxfirefox.exe./firefox./firefox.exe )但沒有成功。

弄清楚了

我沒有意識到 directory() 方法只為新的子進程設置工作目錄,您仍然需要為要運行的可執行文件提供完整路徑。

在這種情況下,以下代碼將起作用:

Process process = new ProcessBuilder("C:\\Program Files\\Mozilla Firefox\\firefox")
                    .directory(new File("C:\\Program Files\\Mozilla Firefox"))
                    .inheritIO()
                    .start();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM