Java进程可以从不同的位置执行吗?

发布于 2024-12-17 10:04:30 字数 721 浏览 0 评论 0原文

我想从不同的位置到我的应用程序 jar 所在的位置创建一个进程,但我不确定是否可能,或者如果可能,如何做到这一点。

例如,这是我正在开发的一个minecraft包装器,

Runtime rt = Runtime.getRuntime();

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

Process pr = rt.exec(proc);

这将从当前位置执行minecraft jar(这使得minecraft地图和服务器配置文件出现在当前文件夹中,这不是我想要的)。


我可以通过将命令“cd”放入bat文件或bash脚本中来实现它,如下所示:

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

然后我的代码将变为

Runtime rt = Runtime.getRuntime();

String proc = "mc.bat";

Process pr = rt.exec(proc);

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡看悲欢离合 2024-12-24 10:04:30

假设您可以使用 Java 1.5 或更高版本,我建议使用 ProcessBuilder 而不是 Runtime。它可以让您轻松设置进程的工作目录。

final Process pr = new ProcessBuilder(
    "java",
    "-Xms512M",
    "-Xmx1024M",
    "-jar",
    "minecraft_server.jar",
    "nogui")
    .directory(new File("minecraft")) //Set the working directory to ./minecraft/
    .start();

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文