read a file inside a Jar file

Hi All,

In this article I will explain how to read a text or csv or prop file from jar. This is very helpful when you export  files and other resources into JAR files to distribute your Java application. So many time we face issues like FileNotFound while accessing the resources which are inside Jar file.

Always use ClassLoader to load any resource from the jar, the reason is thea whenever we are trying to invoke a class from jar, main jvm looks only to the relative position because it tries to load the same class into there, so by using the class loader means we have requested to extract more resources from the jar.
(Please correct me If any of you have some better explanation).

The below example will detailed.
Step 1: Add help.txt in the code base. e.g c:\mytest\help.txt, and add some data into it

Step 2: Write a class and add the below method

public void readFromFile() {
BufferedReader bufferedReader = null;
try {
//Construct Input Stream object, and use the java class classloader to find the resource
InputStream is = getClass().getResourceAsStream(“help.txt“); // pass the resource name
//[NOTE]: Beware that ClassLoader#getResourceAsStream returns null if the resource is not found. This will throw an ugly NPE. So always put a null check before going forward.

//Create a InputStream Reader Object from Input Stream
InputStreamReader isr = new InputStreamReader(is);

// Now pass the Input Stream into Buffered Reader, and read the input and display on the console
bufferedReader = new BufferedReader(isr);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

} catch (FileNotFoundException ex) {
ex.printStackTrace();

} catch (IOException ex) {
ex.printStackTrace();

} finally {
//Close the BufferedReader
try {
if (bufferedReader != null)
bufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Note [Structure of Jar for this Example]
myjar.jar
|
– META-INF
– MyClass.class
– help.txt

Hope this helps.


Thanks
R Vashi

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s