HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / I/O / Java Read File from Classpath

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.

package com.howtodoinjava.io;

import java.io.File;
import java.io.IOException;
import java.net.URL;

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
		System.out.println(file.getPath());

		//Read file
		List<String> lines = Files.readAllLines(file.toPath());
		
		System.out.println(lines);
	}
	
	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());
        }
	}
}
E:\devsetup\gitworkspace\Core-Java\bin\demo.txt
[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 !!

Sourcecode Download

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Java IO

  • Java IO Introduction
  • Java How IO works?
  • Java IO vs NIO
  • Java Create File
  • Java Write to File
  • Java Append to File
  • Java Read File
  • Java Read File to String
  • Java Read File to Byte[]
  • Java Make File Read Only
  • Java Copy File
  • Java Copy Directory
  • Java Delete Directory
  • Java Current Working Directory
  • Java Read/Write Properties File
  • Java Read File from Resources
  • Java Read File from Classpath
  • Java Read/Write UTF-8 Data
  • Java Check if File Exist
  • Java Create Temporary File
  • Java Write to Temporary File
  • Java Delete Temporary File
  • Java Read from Console
  • Java Typesafe input using Scanner
  • Java Password Protected Zip
  • Java Unzip with Subdirectories
  • Java Generate SHA/MD5
  • Java Read CSV File
  • Java InputStream to String
  • Java String to InputStream
  • Java OutputStream to InputStream
  • Java InputStreamReader
  • Java BufferedReader
  • Java FileReader
  • Java LineNumberReader
  • Java StringReader
  • Java FileWriter
  • Java BufferedWriter
  • Java FilenameFilter
  • Java FileFilter

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces