Reading a File from Classpath in Java

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

1. Placing the Files in Classpath

The classpath of an application generally contains the 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 to the projects lib folder or add the jar in the project’s 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 the Files from Classpath

To read any file from the classpath in a class, we have to get the reference of the system classloader for that class that is trying to read the file.

System 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());

3. Full and Relative 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 !!

Sourcecode Download


Notify of
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.