Accessing files under .jar in a swing application?

与世无争的帅哥 提交于 2019-12-12 18:54:22

问题


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

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