Java Read File from Classpath

Learn to read a file from classpath in Java. The file can be present at the root of class path location or in any relative sub-directory.

1. Adding files in classpath

The classpath of an application generally contains following locations:

  • Project’s root directory
  • /src/main/resources
  • Any location whose files are copied to /classes folder after project build runs.

If the file is present inside a jar file, add the jar file in the projects lib folder or add the jar in projects classpath.

The important thing to validate is that the file is copied into final build output of the project i.e. jar/war file or ear file.

2. Reading a file from classpath

Reading a file from classpath is simple. We have to get the reference of system classloader for the class which is trying to read the file.

This classloader obviously knows the other paths for the application. Once we have the File reference, we can use a number of ways to read the file.



public class ReadFileFromClasspath 
	public static void main(String[] args) throws Exception 
		//To avoid referring non-static method inside main() static method
		ReadFileFromClasspath instance = new ReadFileFromClasspath();
		File file = instance.getFile("demo.txt");
		//validate file path

		//Read file
		List<String> lines = Files.readAllLines(file.toPath());
	private File getFile(String fileName) throws IOException
		ClassLoader classLoader = getClass().getClassLoader();
        URL resource = classLoader.getResource(fileName);
        if (resource == null) {
            throw new IllegalArgumentException("file is not found!");
        } else {
            return new File(resource.getFile());
[hello world 1, hello world 2, hello world 3]

Where the file contents are:

hello world 1
hello world 2
hello world 3

3. File paths

The file name can be given in two ways i.e. root directory paths and full paths.

  • fileName.txt – searches the file in the root path of the build folder (e.g. /bin, /build, /WEB-INF/classes etc).
  • com/howtodoinjava/io/demo.txt – represent the full path of the file within the build directory. In this case actual file is present in location <project_root>/bin/com/howtodoinjava/io/demo.txt.

Drop me your questions related to reading a file from the classpath in Java.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.