简体   繁体   中英

Java process execution possible from different location?

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM