简体   繁体   English

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

[英]JAR file running from another directory?

I created a JAR file with my Java program. 我用Java程序创建了一个JAR文件。 This piece of code will open a few files inside a dir "Test", which is in the same dir as the JAR file. 这段代码将在目录“ Test”中打开一些文件,该目录与JAR文件位于同一目录中。 Like this: 像这样:

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

If I run via terminal with: java -jar program.jar, it runs perfectly. 如果我通过终端运行:java -jar program.jar,它运行完美。 But if I run graphically (right clicking on the jar file and Open with OpenJDK...), it doesn't work properly. 但是,如果我以图形方式运行(右键单击jar文件并使用OpenJDK打开...),它将无法正常工作。 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? 当我以图形方式运行JAR文件时,它是否可能从另一个目录运行?

By the way, I'm running on Ubuntu. 顺便说一句,我正在Ubuntu上运行。

Yes, you will get another current working directory... There would be two solutions: 是的,您将获得另一个当前的工作目录......将有两个解决方案:

1) Find the cwd by doing this hack: 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) If the files under Test are static (does not change to often) the solution would be to package them inside the jar. 2)如果Test下的文件是静态的(不经常更改),解决方案是将它们打包到jar中。

I'm not sure if this will help, but below is a link to similar JAR question. 我不确定这是否会有所帮助,但下面是类似JAR问题的链接。

Running jar file with source files in another directory 在另一个目录中运行包含源文件的jar文件

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

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