2

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.

Community
  • 1
  • 1
Asif
  • 4,980
  • 8
  • 38
  • 53
  • possible duplicate of [Java: Load a resource contained in a jar](http://stackoverflow.com/questions/574809/java-load-a-resource-contained-in-a-jar) – jtahlborn Apr 06 '12 at 12:53

1 Answers1

6

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.

Russell Zahniser
  • 16,188
  • 39
  • 30
  • Can I use `ClassName.class.getResource()` here? – Asif Apr 06 '12 at 13:05
  • I am using: `MyClass.class.getResource("/resources/files/help/file.html");`, this returns correct path with `System.out.println()` but `NullPointerException` with `textPane.setPage()`. . . ?? – Asif Apr 06 '12 at 13:13
  • @Asif Using the same `String` would fail, since the raw string is not in itself a valid URL. 1) Get `theURL` using `getResource()` 2) Call `pane.setPage(theURL.toString());` – Andrew Thompson Apr 07 '12 at 06:30