2

I'm wanting to create a process from a different location to where my application jar is located but I'm not sure if it's possible or if it is, how to do it.

For example, this is a minecraft wrapper I'm working on

Runtime rt = Runtime.getRuntime();

String proc = "java -Xms512M -Xmx1024M -jar minecraft_server.jar nogui";

Process pr = rt.exec(proc);

This will execute the minecraft jar from the current location (which makes the minecraft map and server configuration files appear in the current folder which is not what I want).


I can achieve it by putting the command 'cd' into a bat file or bash script which looks like:

cd minecraft/
java -Xms512M -Xmx1024M -jar ../minecraft_server.jar nogui

Then my code would become

Runtime rt = Runtime.getRuntime();

String proc = "mc.bat";

Process pr = rt.exec(proc);

Which will execute minecraft.jar from the subdirectory 'minecraft/' which is what I want. However, I'd very much like to do this within the Java application if it's possible, without the use of a batch file/bash script.

Sam
  • 2,771
  • 2
  • 28
  • 41
  • You can see my answer about it in [this question](http://stackoverflow.com/questions/6811522/changing-the-working-directory-of-command-from-java/42281455#42281455) – David Hazani Feb 16 '17 at 18:09

1 Answers1

7

Assuming you can use Java 1.5 or higher, I'd recommend using ProcessBuilder instead of Runtime. It will let you easily set the working directory for the process.

final Process pr = new ProcessBuilder(
    "java",
    "-Xms512M",
    "-Xmx1024M",
    "-jar",
    "minecraft_server.jar",
    "nogui")
    .directory(new File("minecraft")) //Set the working directory to ./minecraft/
    .start();
Jack Edmonds
  • 31,931
  • 18
  • 65
  • 77
  • This is what I'm looking for, however .directory does not expect a parameter – Sam Nov 21 '11 at 17:49
  • @Sam There are two overloads for `directory`. One tells you the current working directory and the other sets it. See http://download.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html#directory%28java.io.File%29 – Jack Edmonds Nov 21 '11 at 17:50
  • Am I correct that this solution does not work with programs defined on system path? For example ANT, which is deifined in my system path. Through console it works fine but when I use this solution, I get exception: `java.io.IOException: Cannot run program "ant" (in directory "C:\composed_projects"): CreateProcess error=2, The system cannot find the file specified` – Indrek Kõue May 10 '12 at 15:08