且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么相对路径在JAR文件的JAVA中不起作用?

更新时间:2023-02-09 23:31:16

我看到闭幕投票说这是

I see the vote to close that says it's a duplicate of this Q&A, but I don't think it explains the specifics of .., so here you go:

..在文件系统上的资源上工作,因为..是文件系统上的实际条目,指向父目录.但这在jar中不存在,因此当您的类&资源包装在一个罐子里.

.. works on resources on the filesystem, because .. is an actual entry on the filesystem, that points to parent directory. But that does not exist within jars, so it won't work to point to "parent package" when your classes & resources are packaged in a jar.

解决方案:如果您可以接受从控制器类到Main类的依赖关系,则可以改为:

Solution: if you can accept the dependency from your controller class to Main class, you can do this instead:

Main.class.getResource("view/SecondaryWindow.fxml")

无论如何,您都需要引用一个在程序包层次结构中足够高的类,或者使用来自根程序包的绝对路径(显然是getClass().getClassLoader().getResource("app/view/SecondaryWindow.fxml")).

In any case you'll need to either reference a class that is high enough in the packages hierarchy, or use an absolute path from root package (getClass().getClassLoader().getResource("app/view/SecondaryWindow.fxml") in your case apparently).