简体   繁体   English

Java进程可以从其他位置执行吗?

[英]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. 我想从我的应用程序jar所在的其他位置创建一个进程,但是我不确定是否可行,如何执行。

For example, this is a minecraft wrapper I'm working on 例如,这是我正在处理的Minecraft包装器

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). 这将从当前位置执行minecraft jar(这会使minecraft地图和服务器配置文件出现在当前文件夹中,这不是我想要的)。


I can achieve it by putting the command 'cd' into a bat file or bash script which looks like: 我可以通过将命令“ cd”放入如下所示的bat文件或bash脚本中来实现:

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. 这将从我想要的子目录“ minecraft /”中执行minecraft.jar。 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. 但是,如果可能的话,我非常希望在Java应用程序中执行此操作,而无需使用批处理文件/ bash脚本。

Assuming you can use Java 1.5 or higher, I'd recommend using ProcessBuilder instead of Runtime . 假设您可以使用Java 1.5或更高版本,建议您使用ProcessBuilder而不是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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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