I'm trying to run a child process in Java while using ProcessBuilder's directory() method. However, whenever I use the directory() method, the program fails, saying the file was not found. However, the file is present in the working 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
When I ommit the directory() method and create a ProcessBuilder like: new ProcessBuilder("C:\\Program Files\\Mozilla Firefox\\firefox")
, it works fine and firefox.exe launches successfully.
This happens both on Windows and Linux.
I've already tried several versions of the launch command (like firefox
, firefox.exe
, ./firefox
, ./firefox.exe
) but with no success.
Figured it out
I didn't realize that the directory() method only sets the working directory for the new child process and you still need to provide a full path for the executable you want to run.
In this case, the following code would work:
Process process = new ProcessBuilder("C:\\Program Files\\Mozilla Firefox\\firefox")
.directory(new File("C:\\Program Files\\Mozilla Firefox"))
.inheritIO()
.start();