HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / I/O / Read file from resources folder

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?

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.

Feedback, Discussion and Comments

  1. Hien Nguyen

    April 15, 2020

    Thank you so much for sharing. This helps me a lot

  2. griffin

    March 13, 2019

    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()));
    		}
    	}
    
  3. ARM

    January 21, 2019

    Solve my problem, thanks!

  4. Aftab

    January 17, 2019

    will this procedure work for a .xlsx file too?

  5. Charl

    September 19, 2017

    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

    • Lokesh Gupta

      September 19, 2017

      Thanks for sharing. Much appreciated !!

  6. sandeep

    August 30, 2017

    Thanks it works !!!

  7. Saul

    May 22, 2017

    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”

  8. Vikas

    November 19, 2016

    Thanks it works

    Vikas

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