Read file from resources folder in Spring Boot

后端 未结 12 1117
盖世英雄少女心
盖世英雄少女心 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: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 lines = reader.lines();
              reponseXML = lines.collect(Collectors.joining("\n"));
    
            }      
          } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
          }
      }
    }
    

提交回复
热议问题