Java:从JAR运行时的文件路径 [英] Java: file path when running from as JAR
问题描述
我有一个Java / JavaFX项目,我使用样式表。
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');
}
当我从Eclipse或Scenebuilder编译并运行它时,它加载正常。但是,当从cmd( java -jar project.jar
)运行我的jar文件时,它会将文件名添加到路径中,并将其更改为:
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
并且显然无法加载它。我如何获得正确的路径,或者从某种方式jar生成的路径中省略jar? jar文件在这里的包文件夹中列为 packagename
。
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
.
推荐答案
假设packageName是来自jar文件根目录的路径,它显然会失败。路径上的 ../
前缀将导致您的相对位置将上升到其父目录,并在 ../ <之后搜索该部分/ code>来自该目录。
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.
在eclipse中,父目录可能是项目目录,而在.jar文件中,它是jar文件本身给出你描述的结果。修复将是使用源目录(在eclipse中的buildpath中配置)。这些sourcepath的结构取决于你,虽然常见的结构如下:
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.
同样,上述内容并不要求使java项目完美,尽管这是常见的做法。
Again the above is no requirement to make a java project perfect, though it is common practise.
可能另一个修复方法是根本不使用 ../
,虽然我不确定。可能只是.jar文件修复。
Propably another fix would be to use no ../
at all, although Im not sure about that. It might be a .jar-file-only fix.
这篇关于Java:从JAR运行时的文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!