If you need to access a text file inside a JAR, the code is not self evident, but easy. To load an XML file, for example, you have to use the code below:
ClassLoader cl = this.getClass().getClassLoader();
java.io.InputStream in = cl.getResourceAsStream("properties.xml");
The file "properties.xml" is inside the "application.jar" file, in the same package of the class where it is called. You can put this file in another package, but it will be more difficult to define the exact location of it. It's easier and coherent if you keep the caller and the resource in the same place.
When you want to access images from the jar file the code is a little bit different. The example below shows how to create an image icon to illustrate swing components.
JButton btRemove = new JButton(new ImageIcon(SearchTab.class.getResource("remove.png"));
Again, the figure "remove.png" is in the same package of the class "SearchTab.class".
The Java API doesn't provide one form to change files inside jar files. We can read and manipulate the content, but not save it back in the same file. So, this is a solution for read-only needs.
4 comments: