Read file from resources folder in Spring Boot

We Are Going To Discuss About Read file from resources folder in Spring Boot. So lets Start this Java Article.

Read file from resources folder in Spring Boot

Advertisements
  1. Read file from resources folder in Spring Boot

    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.

  2. Read file from resources folder in Spring Boot

    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.

Solution 1

Advertisements

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

enter image description here

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.

Original Author John Of This Content

Solution 2

Advertisements

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:

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");

Original Author Serhii Povísenko Of This Content

Solution 3

Advertisements

if you have for example config folder under Resources folder
I tried this Class working perfectly hope be useful

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

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

Original Author Ismail Of This Content

Solution 4

Advertisements

Spent way too much time coming back to this page so just gonna leave this here:

File file = new ClassPathResource("data/data.json").getFile();

Original Author Emmanuel Osimosu Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment