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:
In order to read example.xml from ClasspathFileReader.java, we should first add resource folder to classpath and then read it as the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package com.programmer.gate; import java.io.File; import java.net.URL; /** * This class reads a resource file from classpath. * * @author Hussein * */ public class ClasspathFileReader { private static final String CONFIG_FILE = "/example.xml"; public File readFileFromClasspath() { URL fileUrl = getClass().getResource(CONFIG_FILE); return new File(fileUrl.getFile()); } } |
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.
[…] this tutorial for more […]
[…] tutorial explains very well the possible ways of reading a resource file from classpath in a java […]
Thanks this was a help.