How to read files from classpath in Java

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

1. Add file to the 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 the 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.

3. 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 the 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 a 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 the 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.

0 0 votes
Article Rating

Hussein Terek

Owner of programmergate.com, I have a passion for software engineering and everything related to Java environment.

guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] this tutorial for more […]

trackback

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

Antoine SAMAHA
Antoine SAMAHA
2 years ago

Thanks this was a help.