Read file from resources folder

Java examples to read a file from the resources folder in either a simple Java application or a Spring MVC / Boot application.

Table of Contents

1. Setup
2. ClassLoader.getResource()
3. ResourceUtils.getFile()

1. Setup

Below image describes the folder structure used in this example. Notice the file sample.txt is in /src/main/resources folder.

Read file from resources folder
Read file from resources folder

2. ClassLoader getResource() and getResourceAsStream()

Methods in the classes Class and ClassLoader provide a location-independent way to locate resources. We can read a file from the application’s resources package by using ClassLoader reference.

The method getResource() returns a URL for the resource. If the resource does not exist or is not visible due to security considerations, the methods return null.

The getResource() and getResourceAsStream() methods find a resource with a given name. They return null if they do not find a resource with the specified name.

  • getResourceAsStream() returns an InputStream for the resource.
  • getResource() returns a URL for the resource.

Example 1: Java program to read a file from resources folder using getResource() method

package com.howtodoinjava.demo;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class ReadResourceFileDemo 
{
	public static void main(String[] args) throws IOException 
	{
		String fileName = "config/sample.txt";
		ClassLoader classLoader = getClass().getClassLoader();

		File file = new File(classLoader.getResource(fileName).getFile());
		
		//File is found
		System.out.println("File Found : " + file.exists());
		
		//Read File Content
		String content = new String(Files.readAllBytes(file.toPath()));
		System.out.println(content);
	}
}

Program output:

File Found : true
Test Content

Example 2: Java program to read a file from resources folder using getResourceAsStream() method

package com.howtodoinjava.demo;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import org.apache.commons.io.IOUtils;

public class ReadResourceFileDemo 
{
	public static void main(String[] args) throws IOException 
	{
		String fileName = "config/sample.txt";
		ClassLoader classLoader = getClass().getClassLoader();

		try (InputStream inputStream = classLoader.getResourceAsStream(fileName)) {
			
			String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
			System.out.println(result);

        } catch (IOException e) {
            e.printStackTrace();
        }
	}
}

Program output:

Test Content

3. ResourceUtils.getFile()

If your application happens to be Spring WebMVC or Spring Boot application then you may directly take advantage of ResourceUtils class.

Example 3: Java program to read a file from resources folder using ResourceUtils

File file = ResourceUtils.getFile("classpath:config/sample.txt")

//File is found
System.out.println("File Found : " + file.exists());

//Read File Content
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);

Program output:

File Found : true
Test Content

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

9 thoughts on “Read file from resources folder”

  1. Works either from filesystem and JAR:

    	public static void main(String[] args) throws IOException {
    
    		String resourceFile = "resource/test_resource.txt";
    
    		InputStream resourceStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceFile);
    
    		if (resourceStream != null) {
    			BufferedReader resReader = new BufferedReader(new InputStreamReader(resourceStream));
    			System.out.println(resReader.lines().collect(Collectors.joining()));
    		}
    	}
    
    Reply
  2. The class loader method works when I run it in IDE, but not when the application is packaged as a jar file. I had to use a ZIP file system to load it from a jar file e.g

    	private byte[] loadData() throws Exception {
    
    		String relativePath = "META-INF/somebinaryfile.bmp";
    		URI resource = getClass().getClassLoader().getResource(relativePath).toURI();
    
    		byte[] data = null;
    		try(FileSystem jarFileSystem = FileSystems.getFileSystem(resource)) {
    			data = readDataFromFile(relativePath, jarFileSystem);
    		} catch (FileSystemNotFoundException e) {
    			 Map<String, String> env = new HashMap<String, String>();
    			 env.put("create", "true");
    			try (FileSystem jarFileSystem = FileSystems.newFileSystem(resource, env)) {
    				data = readDataFromFile(relativePath, jarFileSystem);
    			}
    		}
    		return data;
    	}
    
    	private byte[] readDataFromFile(String fileName, FileSystem jarFileSystem) throws IOException {
    
    		Path path = jarFileSystem.getPath(fileName);
    		byte[] data = Files.readAllBytes(path);
    		return data;
    	}
    

    Also see this: https://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html

    Reply
  3. not working for me, I’m getting this error “Exception in thread “main” java.lang.NullPointerException” and if I try using the filename without folder the error is “\target\classes\sample.txt”

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.