在Swing应用程序中访问.jar下的文件? [英] Accessing files under .jar in a swing application?
问题描述
请参阅我的上一个问题,我想问一下如何读取其他文件
文件夹放入类似的.jar
.
Referring to my previous question, I want to ask that how can I read a file in different
folder into the similar .jar
.
该问题提供了文件夹层次结构和详细信息. 我的主要问题是一行代码:
The folder hierarchy and details are provided with that question. My main problem is with a line of code:
JTextPane textPane = ... //general initialization
textPane.setPage("path/file.html");
问题是我必须将那个file.html保留在我的.jar中.
The problem is I have to keep that file.html in my .jar.
此外,我想了解有关此主题的建议.
Moreover I would like to know suggestions on this topic.
推荐答案
要在JAR中加载资源,可以使用Class.getResource()
.从不在JAR中的普通文件夹结构进行加载时,此方法同样有效:
For loading resources in a JAR, you can use Class.getResource()
. This works equally well when loading from an ordinary folder structure not in a JAR:
textPane.setPage(ThisClass.class.getResource("relative/path/to/file.html"));
此处的路径来自ThisClass.class
所在的文件夹.通常最好显式地命名该类而不是使用this.getClass()
,如果调用此方法,则最终可能会在不同的位置(并且是非预期的)一个子类.
The path here is from whatever folder ThisClass.class
is in. It is generally better to explicitly name the class rather than using this.getClass()
, which may end up looking in a different (and unintended) location if this method is called for a subclass.
这篇关于在Swing应用程序中访问.jar下的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!