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.

1
  • You can see my answer about it in this question Commented Feb 16, 2017 at 18:09

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

3 Comments

This is what I'm looking for, however .directory does not expect a parameter
@Sam There are two overloads for directory. One tells you the current working directory and the other sets it. See download.oracle.com/javase/1.5.0/docs/api/java/lang/…
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.