JAR 文件从另一个目录运行?

发布于 2024-10-03 09:01:44 字数 322 浏览 1 评论 0原文

我用 Java 程序创建了一个 JAR 文件。这段代码将打开“Test”目录中的几个文件,该目录与 JAR 文件位于同一目录中。像这样:

/
 -- program.jar
 -- /Test
     -- *

如果我通过终端运行:java -jar program.jar,它运行完美。但是如果我以图形方式运行(右键单击 jar 文件并使用 OpenJDK 打开...),它就无法正常工作。就像我从另一个目录运行一样。

当我以图形方式运行 JAR 文件时,它是否可能从另一个目录运行?

顺便说一句,我在 Ubuntu 上运行。

I created a JAR file with my Java program. This piece of code will open a few files inside a dir "Test", which is in the same dir as the JAR file. Like this:

/
 -- program.jar
 -- /Test
     -- *

If I run via terminal with: java -jar program.jar, it runs perfectly. But if I run graphically (right clicking on the jar file and Open with OpenJDK...), it doesn't work properly. Just like if I ran from another directory.

Is it possible that when I run the JAR file graphically it's running from another directory?

By the way, I'm running on Ubuntu.

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

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

发布评论

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

评论(2

逆光飞翔i 2024-10-10 09:01:44

是的,您将获得另一个当前工作目录...有两种解决方案:

1) 通过执行此 hack 查找 cwd:

    public class Test {
        public static void main(String... args) { 

            ClassLoader cl = Test.class.getClassLoader();
            String f = cl.getResource("").getFile();

            File cwd = new File(f);

            if (cwd.toString().endsWith("!"))
                cwd = cwd.getParentFile();

            JOptionPane.showMessageDialog(null, cwd);
        }
    }

2) 如果 Test 是静态的(不会经常更改),解决方案是将它们打包到 jar 中。

Yes, you will get another current working directory... There would be two solutions:

1) Find the cwd by doing this hack:

    public class Test {
        public static void main(String... args) { 

            ClassLoader cl = Test.class.getClassLoader();
            String f = cl.getResource("").getFile();

            File cwd = new File(f);

            if (cwd.toString().endsWith("!"))
                cwd = cwd.getParentFile();

            JOptionPane.showMessageDialog(null, cwd);
        }
    }

2) If the files under Test are static (does not change to often) the solution would be to package them inside the jar.

凉风有信 2024-10-10 09:01:44

我不确定这是否有帮助,但下面是类似 JAR 问题的链接。

使用另一个目录中的源文件运行 jar 文件

I'm not sure if this will help, but below is a link to similar JAR question.

Running jar file with source files in another directory

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