Search code examples
javaexecutableworking-directorylaunching-application

Executing .exe file in Java in separate directory


I want to launch games from my apps in Windows. Many of these games rely on local files for configurations.

This is currently how I run/execute files outside of my application

Process r = Runtime.getRuntime().exec("cmd /c start " + gamePATH);

I have also tried just putting gamePath as the command, yet I still get this error from the halo PC game:

Cannot Find "C:\...Directory containing my Java app...\config.txt"

It seems the "current directory" when java executes is the location where it is running from. I tried this with no progress:

Process a = Runtime.getRuntime().exec("cmd /c cd " + gamePATH.subSequence(0, gamePATH.lastIndexOf("\\")+1));

Which would on the command line set the current directory to the directory containing the executable. Again that did not work, so if possible any guidance would be appreciated


Solution

  • You want to look at Process Builder. In particular, you want to set the working directory using the ProcessBuilder.directory(File) method. You execute it using the start() method.

    For example:

    final ProcessBuilder pb = new ProcessBuilder("theExecutable");
    pb.directory(new File("the/working/directory/path"));
    final Process p = pb.start();