Read file from resources folder in Spring Boot

后端 未结 12 1120
盖世英雄少女心
盖世英雄少女心 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.

提交回复
热议问题