Java – Read files from classpath

In this article, we show how to read a resource file from classpath in java.

1. Add file to classpath

Before reading the file, you have to add it to the classpath:

  • If the file to be read exists under a specific folder inside the project structure, then just add the parent folder to classpath and its children will be automatically added.
  • If the file to be read exists under a third party jar file, then just add the jar file to the classpath.

2. Double check the build directory

In order to make sure that the resource file is successfully added to the classpath, double check if the file is generated under the build directory of the project.

The build directory differs based on the type of the application. In stand-alone applications, the default build directory is bin which resides under the root path of the project, however for web applications, the default build directory is WEB-INF/classes.

You can always check and customize the build directory of your project through:

Right Click project -> properties -> Java Build Path -> Source tab -> Default output folder

If the resources exist under the build directory, then you’re ready to read them from the classes or servlets.

2. Read resource file in java

Suppose we have the following project structure:

Read resource file in java

In order to read example.xml from ClasspathFileReader.java, we should first add resource folder to classpath and then read it as the following:

In the above example we use getClass().getResource() , this method tries to read the resource file from the root path of the build folder (i.e. /bin, /build, /WEB-INF/classes) in case the file name starts with forward slash “/”, otherwise it tries to read the file from the same package of the class itself  (i.e. com.programmer.gate).

P.S: When defining the file name in the java class, make sure to take the full path of the generated file under build directory including all subfolders, so if example.xml is generated under /bin/xml/example.xml then the file name should be defined as /xml/example.xml.

 

husseinterek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
0 Comment authors
Getting the inputstream from a classpath resource (XML file) - QuestionFocusHow to really read text file from classpath in Java - ExceptionsHub Recent comment authors
newest oldest most voted
trackback

[…] this tutorial for more […]

trackback

[…] tutorial explains very well the possible ways of reading a resource file from classpath in a java […]