Java:如何知道 jar 位于 Linux 中的位置

发布于 2024-08-05 02:15:25 字数 115 浏览 11 评论 0原文

在 Linux 中,JVM 将工作目录设置为用户的主文件夹。 在 Windows 中,这是 jar 所在的文件夹。 如何找到 jar (来自我的应用程序) 所在位置以更改工作目录?

马丁

In Linux, the JVM sets the working direcory equal to the homefolder from the user.
In Windows is this the folder where the jar is located.
How can I find where the jar (from my app) is located to change the working dir?

Martijn

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

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

发布评论

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

评论(2

哭了丶谁疼 2024-08-12 02:15:25

尝试使用以下代码获取 jar 的路径:

String path = YourClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();

然后您可以使用以下方法删除“*.jar”部分:

path=path.substring(0, path.lastIndexOf('/')+1);

当我需要在 jar 所在的同一目录中打开文件时,我在 java 游戏中遇到了同样的问题。

linux下双击jar打不开文件。当然,您可以打开命令行并将目录更改为 jar 目录,然后从那里运行 jar,但我需要双击该 jar。

Try obtaining the path to the jar with this code:

String path = YourClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();

Then you can remove the "*.jar" part with:

path=path.substring(0, path.lastIndexOf('/')+1);

I had the same problem with a java game when I needed to open a file in the same directory the jar was.

Double clicking the jar in linux didn't open the file. Of course you can open a command line and change dir to the jar dir and then run the jar from there but I needed to double click the jar.

-残月青衣踏尘吟 2024-08-12 02:15:25

在这两种情况下,它都是实际的目录。在 Windows 下,如果您从资源管理器执行它,实际目录会自动设置为 jar 的基本目录。在 Linux 下,主目录是 GUI 的实际目录。要设置目录,请编写一个简短的 shell 脚本,该脚本设置实际目录(使用 cd 命令),然后执行 jar(使用 javaw -jar xyz.jar)。

In both cases it is the actual directory. Under windows automatically the actual directory is set to the base-dir of the jar, if you execute it from explorer. Under linux the home-directory is the actual directory for your GUI. To set the directory write a short shell-script, which sets the actual directory (with the cd-command) and then executes the jar (with javaw -jar xyz.jar).

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