10 Mar 2012

Reading a text file from a JAR file.


The InputStream and OutputStream of java.io package can be used to read the content of a text file and write to the text file respectively. But when a text file is bundled inside a jar file , Is this possible to read that text file (which is in a jar file) ? In this post we will find out if that is possible (Of Course) or not.

Lets say i have a text file "poi.txt" having its content  as "I Love Java Programming ". And it is placed inside a jar file "jkl.jar" using following command
                         cmd>jar cf  jkl.jar  poi.txt
The the task is to read poi.txt from within the jkl.jar file.The java.io.File class is used to represent a file but for jar file this does not work.

 The java.util.jar package is the one to look for when you are dealing with the jar file. This package contains the classes like JarFile and JarEntry  which can be used to get the reference of any file which is placed inside the jar file.
Before i begin further it should be noted that the jar file must be in the CLASSPATH. Here is the code which read the poi.text file from a jar file and print the "I Love Java Programming ".



The JarFile jf = new JarFile(jarFile); gets the reference of a "jkl.jar" file in the current directory. The content of the jar file are represented as a entry in the jar file.It means "poi.txt"is an entry in the jar file. the JarEntry entry = jf.getJarEntry(txtFile); is used to get the reference of "poi.txt" file.which is inside of jar file.
Now we want to read from poi.txt , so first get the inputstream using InputStreamin = jf.getInputStream(entry); second is to read using read() method. And it prints the "I Love Java Programming" as an output.

That was something "cool" thing to learn. Hope you will find it useful.
Please share your comment.








No comments:

Post a Comment