Read file from resources folder in Spring Boot

后端 未结 12 1038
盖世英雄少女心
盖世英雄少女心 2020-11-28 06:50

I\'m using Spring Boot and json-schema-validator. I\'m trying to read a file called jsonschema.json from the resources folder. I\'ve t

相关标签:
12条回答
  • 2020-11-28 07:15

    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.

    0 讨论(0)
  • 2020-11-28 07:17

    For me, the bug had two fixes.

    1. Xml file which was named as SAMPLE.XML which was causing even the below solution to fail when deployed to aws ec2. The fix was to rename it to new_sample.xml and apply the solution given below.
    2. Solution approach https://medium.com/@jonathan.henrique.smtp/reading-files-in-resource-path-from-jar-artifact-459ce00d2130

    I was using Spring boot as jar and deployed to aws ec2 Java variant of the solution is as below :

    package com.test;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.core.io.Resource;
    
    
    public class XmlReader {
    
        private static Logger LOGGER = LoggerFactory.getLogger(XmlReader.class);
    
      public static void main(String[] args) {
    
    
          String fileLocation = "classpath:cbs_response.xml";
          String reponseXML = null;
          try (ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext()){
    
            Resource resource = appContext.getResource(fileLocation);
            if (resource.isReadable()) {
              BufferedReader reader =
                  new BufferedReader(new InputStreamReader(resource.getInputStream()));
              Stream<String> lines = reader.lines();
              reponseXML = lines.collect(Collectors.joining("\n"));
    
            }      
          } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
          }
      }
    }
    
    0 讨论(0)
  • 2020-11-28 07:19

    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);
    
    0 讨论(0)
  • 2020-11-28 07:19

    create json folder in resources as subfolder then add json file in folder then you can use this code :

    import com.fasterxml.jackson.core.type.TypeReference;

    InputStream is = TypeReference.class.getResourceAsStream("/json/fcmgoogletoken.json");

    this works in Docker.

    0 讨论(0)
  • 2020-11-28 07:24

    Very short answer: you are looking for your property in the scope of a particular class loader instead of you target class. This should work:

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

    Also, see this:

    • 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 can be an issue if the project has been compiled on one machine and after that has been launched on another or you run your app in Docker. In this case, paths to your resource folder can be invalid. In this case it would be better to determine paths to your resources at 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 in your tests, for example, 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");
    
    0 讨论(0)
  • 2020-11-28 07:27

    Below is my working code.

    List<sampleObject> list = new ArrayList<>();
    File file = new ClassPathResource("json/test.json").getFile();
    ObjectMapper objectMapper = new ObjectMapper();
    sampleObject = Arrays.asList(objectMapper.readValue(file, sampleObject[].class));
    

    Hope it helps one!

    0 讨论(0)
提交回复
热议问题