Java: file path when running from as JAR

 ̄綄美尐妖づ 提交于 2019-12-11 04:59:59

问题


I have a Java/JavaFX project where I use style sheets.

Images from stylesheets will get loaded as follows:

#pane {
-fx-background-image:url('../packagename/image.jpg');
 }

It loads fine when I compile and run it from Eclipse or Scenebuilder. However, when running my jar file from the cmd (java -jar project.jar), it adds the file name to the path, changing it to:

project.jar/packagename/image.jpg

and obviously failing to load it. How do I get the correct path, or alternatively, omit the jar from the somehow jar generated path? The jar file is in the package folder here outlined as packagename.


回答1:


Add all of the images to a source folder. Since you said you're using Eclipse, just right click on your project -> New Source Folder. Name it something like res. Copy and paste all of your images in there.




回答2:


Assuming the "packageName" is a path from the root of the jar file, it will obviously fail. The ../ prefix on your path will cause your relative location will go up to its parent directory, and search the part after the ../ from that directory.

In eclipse the parent directory would propably be the project directory, while in your .jar file, it is the jar file itself giving the result you described. A fix would be to use source directories (configured in the "buildpath" in eclipse). The structure of these sourcepath's is up to you, though a common structure is as follows:

Root (either the eclipse project folder, or the .jar file
   | src
   |   | main
   |      | java // usually here goes all the code
   |      | resources  // and here goes all the resources the code needs.

Again the above is no requirement to make a java project perfect, though it is common practise.

Propably another fix would be to use no ../ at all, although Im not sure about that. It might be a .jar-file-only fix.



来源:https://stackoverflow.com/questions/41231256/java-file-path-when-running-from-as-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!