After spending a lot of time trying to resolve this issue, finally found a solution that works. The solution makes use of Spring's ResourceUtils. Should work for json files as well.

Thanks for the well written page by Lokesh Gupta : Blog

package utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.io.File;


public class Utils {

    private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class.getName());

    public static Properties fetchProperties(){
        Properties properties = new Properties();
        try {
            File file = ResourceUtils.getFile("classpath:application.properties");
            InputStream in = new FileInputStream(file);
            properties.load(in);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
        return properties;
    }
}

To answer a few concerns on the comments :

Pretty sure I had this running on Amazon EC2 using java -jar target/image-service-slave-1.0-SNAPSHOT.jar

Look at my github repo : https://github.com/johnsanthosh/image-service to figure out the right way to run this from a JAR.

Answer from John on Stack Overflow
🌐
Baeldung
baeldung.com › home › spring › access a file from the classpath in a spring application
Access a File from the Classpath using Spring | Baeldung
March 26, 2025 - As a caveat, there is another way to retrieve resources in Spring, but the ResourceUtils Javadoc is clear that the class is mainly for internal use. ... public File loadEmployeesWithSpringInternalClass() throws FileNotFoundException { return ResourceUtils.getFile( "classpath:data/employees.dat"); } We should carefully consider the rationale, as it’s probably better to use one of the standard approaches above. Once we have a Resource, it’s easy for us to read the contents.
🌐
HowToDoInJava
howtodoinjava.com › home › spring boot 2 › read a file from resources in spring boot
Read a File from Resources in Spring Boot
August 27, 2023 - Learn to read a file from the ‘/resources’ folder in a Spring boot application using ClassPathResource class, ResourceLoader interface or @Value annotation.
Top answer
1 of 16
200

After spending a lot of time trying to resolve this issue, finally found a solution that works. The solution makes use of Spring's ResourceUtils. Should work for json files as well.

Thanks for the well written page by Lokesh Gupta : Blog

package utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.io.File;


public class Utils {

    private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class.getName());

    public static Properties fetchProperties(){
        Properties properties = new Properties();
        try {
            File file = ResourceUtils.getFile("classpath:application.properties");
            InputStream in = new FileInputStream(file);
            properties.load(in);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
        return properties;
    }
}

To answer a few concerns on the comments :

Pretty sure I had this running on Amazon EC2 using java -jar target/image-service-slave-1.0-SNAPSHOT.jar

Look at my github repo : https://github.com/johnsanthosh/image-service to figure out the right way to run this from a JAR.

2 of 16
90

Very short answer: you are looking for the resource in the scope of a classloader's class instead of your target class. This should work:

File file = new File(getClass().getResource("jsonschema.json").getFile());
JsonNode mySchema = JsonLoader.fromFile(file);

Also, that might be helpful reading:

  • What is the difference between Class.getResource() and ClassLoader.getResource()?
  • Strange behavior of Class.getResource() and ClassLoader.getResource() in executable jar
  • Loading resources using getClass().getResource()

P.S. there is a case when a project compiled on one machine and after that launched on another or inside Docker. In such a scenario path to your resource folder would be invalid and you would need to get it in runtime:

ClassPathResource res = new ClassPathResource("jsonschema.json");    
File file = new File(res.getPath());
JsonNode mySchema = JsonLoader.fromFile(file);

Update from 2020

On top of that if you want to read resource file as a String, for example in your tests, you can use these static utils methods:

public static String getResourceFileAsString(String fileName) {
    InputStream is = getResourceFileAsInputStream(fileName);
    if (is != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        return (String)reader.lines().collect(Collectors.joining(System.lineSeparator()));
    } else {
        throw new RuntimeException("resource not found");
    }
}

public static InputStream getResourceFileAsInputStream(String fileName) {
    ClassLoader classLoader = {CurrentClass}.class.getClassLoader();
    return classLoader.getResourceAsStream(fileName);
}

Example of usage:

String soapXML = getResourceFileAsString("some_folder_in_resources/SOPA_request.xml");
🌐
Initial Commit
initialcommit.com › blog › spring-read-files-from-classpath
Spring – Read files from classpath - Initial Commit
Using ClassPathResource class provided by Spring Core, you can read a resource file using both absolute and relative paths.
🌐
Medium
medium.com › @arthurraposodev › test-694cf70bd013
Java Spring Boot: How to Read from a File in Resources | by Arthur Raposo | Medium
November 21, 2023 - It is important to note that since @Value is populated after bean instantiation, this will not work if used inside a constructor or while Spring is still setting up the context. In both cases, it is possible to read from the Resource interface to a string using a method like the following: public static String asString(Resource resource) { try (Reader reader = new InputStreamReader(resource.getInputStream(), UTF_8)) { return FileCopyUtils.copyToString(reader); } catch (IOException e) { throw new UncheckedIOException(e); } } ClassPathResource is a part of the Spring framework that provides another way to access files within the classpath, like those in the resources directory.
🌐
Smarterco
smarterco.de › java-load-file-from-classpath-in-spring-boot
Java: Load file from classpath in Spring Boot - smarterco.de
June 16, 2015 - ", e); } } @PreDestroy public void ... you would like to load a file from classpath in a Spring Boot JAR, then you have to use the resource.getInputStream() method to retrieve it as a InputStream....
🌐
Mkyong
mkyong.com › home › spring › spring – read file from resources folder
Spring - Read file from resources folder - Mkyong.com
April 13, 2019 - import org.springframework.cor... ClassPathResource("android.png"); InputStream input = resource.getInputStream(); File file = resource.getFile();...
🌐
Oreate AI
oreateai.com › blog › spring-boot-reading-files-from-the-classpath › 62d28756c57eaeeac56bbe0e17879b43
Spring Boot - Reading Files From the Classpath - Oreate AI Blog
December 22, 2025 - // Method 1: Get File or Stream this.getClass().getResource("/") + fileName; this.getClass().getResourceAsStream(fileName); // Method 2: Get File File file = org.springframework.util.ResourceUtils.getFile("classpath:test.txt");
Find elsewhere
🌐
Medium
medium.com › @trivajay259 › read-a-file-from-resources-in-spring-boot-0ccd6d4be1d6
Read a File from Resources in Spring Boot | by Ajay Kumar | Medium
May 5, 2025 - @Autowired private ResourceLoader resourceLoader; public void method(){ Resource resource = resourceLoader.getResource("classpath:filename.txt"); File file = resource.getFile()); //... } //OR Resource resource = new ClassPathResource("classpath:filename.txt"); //OR @Value("classpath:filename.txt") Resource resource; To learn more about resource resolution in Spring, continue reading this tutorial.
🌐
YouTube
youtube.com › alex gutjahr | tech tutorials
How To Access Files on the Classpath with Spring Boot 3 - YouTube
Hey friends! A quick overview of how to access files from your Spring Boot application.🍃 *Code & Resources*Grab the code for this tutorial here https://axgr...
Published   December 12, 2023
Views   442
🌐
GeeksforGeeks
geeksforgeeks.org › java › read-a-file-from-the-classpath-in-java
How to Read a File From the Classpath in Java? - GeeksforGeeks
July 23, 2025 - // Java Program to Read a File from the Classpath import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; // Driver Class public class MyClass { // Main Function public static void main(String[] args) { // Filename String filePath = "MyFile.txt"; // Loading the current class's class loader for inputStream InputStream inputStream = MyClass.class.getClassLoader().getResourceAsStream(filePath); // Checking if the class loaded successfully if (inputStream != null) { try (BufferedReader reader = new BufferedReader(new InputStreamReade
🌐
GeeksforGeeks
geeksforgeeks.org › advance java › read-file-from-resources-folder-in-spring-boot
Read file from Resources Folder in Spring Boot - GeeksforGeeks
November 3, 2025 - ResourceLoader helps load files from the classpath, filesystem, or URL. Always close BufferedReader after reading the file.
🌐
Simplesolution
simplesolution.dev › java-spring-boot-classpathresource
Spring Boot Read File from resources using ClassPathResource
... Create a new class named TestReadFile and use ClassPathResource class to read data.json file then print the log message file content as following code. ... package dev.simplesolution; import java.io.InputStream; import org.slf4j.Logger; ...
🌐
Apps Developer Blog
appsdeveloperblog.com › home › spring framework › spring boot › read a file from the resources folder in spring boot
Read a File From the Resources Folder in Spring Boot - Apps Developer Blog
August 27, 2022 - The ClassPathResource class contains useful methods for reading the resources in a Spring application. import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.FileCopyUtils; import java.io.*; import java.nio.charset.StandardCharsets; @SpringBootApplication public class DemoApplication { public static void main(String[] args) throws IOException { SpringApplication.run(DemoApplication.class, args); readF
🌐
Spring
docs.spring.io › spring-framework › docs › 3.2.x › spring-framework-reference › html › resources.html
6. Resources
This class represents a resource which should be obtained from the classpath. This uses either the thread context class loader, a given class loader, or a given class for loading resources. This Resource implementation supports resolution as java.io.File if the class path resource resides in ...
🌐
Medium
medium.com › codex › accessing-resource-files-in-spring-boot-a-comprehensive-guide-eab958eb8f9c
Accessing Resource Files in Spring Boot: A Comprehensive Guide | by Igor Venturelli | CodeX | Medium
November 28, 2024 - The key point here is the use of the classpath: prefix to indicate that the file is located in the classpath. Spring Boot allows you to inject the contents of a file directly into a field using the @Value annotation.
🌐
Steranka Blog
steranka.com › 2024 › 10 › 25 › java-read-file-from-classpath.html
Java - Read file from classpath | Steranka Blog
October 25, 2024 - Important TIPS when reading files on classpath You can read a resource using multiple approaches (not all work the same). AClass.class.getClassLoader().getResourceAsStream(file); // preferred ClassLoader.getSystemResourceAsStream(resourcePath) AClass.class.getResourceAsStream() Depending on h~~~~ow the code is written you either NEED to use a leading slash in the name of the resource loaded or don’t need to use one.
🌐
Spring
docs.spring.io › spring-framework › docs › 2.5.x › reference › resources.html
Chapter 4. Resources
This class represents a resource which should be obtained from the classpath. This uses either the thread context class loader, a given class loader, or a given class for loading resources. This Resource implementation supports resolution as java.io.File if the class path resource resides in ...