How to read files from CLASSPATH in Java

This is one learn­ing from my pre­vi­ous project in 2009.

The most plat­form-inde­pen­dent and flex­i­ble way in Java to load resources such as files is to read the resource from CLASSPATH. This way, as long as the resource’s loca­tion is added to CLASSPATH, the resource can be any­where on the disk.

Java pro­vides a method named getRe­source­AsStream() for this pur­pose. This method is present in both Class and Class­Loader class­es. There are very sub­tle dif­fer­ences between these two meth­ods, which if not under­stood prop­er­ly, will lead to con­fu­sion.

Using ClassLoader.getResourceAsStream(),

While using ClassLoader.getResourceAsStream() method, the name of the resource should not be pre­ced­ed with lead­ing slash (/) in any cir­cum­stances. This is because from Class­Loader all paths are already absolute and there is no con­text from which they could be rel­a­tive. There­fore the ques­tion of whether or not to use lead­ing slash (/) should not arise. If you add lead­ing slash in front of the resource name, Input­Stream will always be null.

To use ClassLoader.getResourceAsStream(),

[1] In CLASSPATH add the direc­to­ry where someFile.txt resides.

[2] Use the fol­low­ing code to read the resource.

Input­Stream in = this.getClass().getClassLoader().getResourceAsStream(“SomeFile.txt”);

Using Class.getResourceAsStream(),

(a) If the resource and the Java class which is read­ing the resource are in the same direc­to­ry then there is no need to use a lead­ing slash (/). You can direct­ly use the fol­low­ing line of code to read the resource.

Input­Stream in = this.getClass().getResourceAsStream(“SomeFile.txt”);

(b) If the resource and the Java class which is read­ing the resource are in dif­fer­ent direc­to­ries then you have to use a lead­ing slash (/).

[1] In CLASSPATH add the direc­to­ry where someFile.txt resides.

[2] Use the fol­low­ing code to read the resource.

Input­Stream in = this.getClass().getResourceAsStream(“/SomeFile.txt”);

Impor­tant Note:

When we are using a man­aged envi­ron­ment i.e. in case of appli­ca­tion servers, CLASSPATH entry has to be made in the server’s start up script. For exam­ple in WebLog­ic, CLASSPATH entry has to be append­ed to the one already present in startWebLogic.cmd (startWebLogic.sh in Unix envi­ron­ments) in DOMAIN_HOME\bin direc­to­ry.

Ref­er­ence:

1.http://stackoverflow.com/questions/1464291/how-to-really-read-text-file-from-classpath-in-java

Categories:

Tags:

Leave a Reply

%d bloggers like this: