问题
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");
The problem is I have to keep that file.html in my .jar.
Moreover I would like to know suggestions on this topic.
回答1:
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"));
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.
来源:https://stackoverflow.com/questions/10043708/accessing-files-under-jar-in-a-swing-application