Read file from resources folder in Spring Boot

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

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

    File file = new ClassPathResource("data/data.json").getFile();
    
    0 讨论(0)
  • Here is my solution. May help someone;

    It returns InputStream, but i assume you can read from it too.

    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("jsonschema.json");
    
    0 讨论(0)
  • 2020-11-28 07:30

    stuck in the same issue, this helps me

    URL resource = getClass().getClassLoader().getResource("jsonschema.json");
    JsonNode jsonNode = JsonLoader.fromURL(resource);
    
    0 讨论(0)
  • 2020-11-28 07:31

    The simplest method to bring a resource from the classpath in the resources directory parsed into a String is the following one liner.

    As a String(Using Spring Libraries):

             String resource = StreamUtils.copyToString(
                    new ClassPathResource("resource.json").getInputStream(), defaultCharset());
    

    This method uses the StreamUtils utility and streams the file as an input stream into a String in a concise compact way.

    If you want the file as a byte array you can use basic Java File I/O libraries:

    As a byte array(Using Java Libraries):

    byte[] resource = Files.readAllBytes(Paths.get("/src/test/resources/resource.json"));
    
    0 讨论(0)
  • 2020-11-28 07:35

    See my answer here: https://stackoverflow.com/a/56854431/4453282

    import org.springframework.core.io.Resource;
    import org.springframework.core.io.ResourceLoader;
    

    Use these 2 imports.

    Declare

    @Autowired
    ResourceLoader resourceLoader;
    

    Use this in some function

    Resource resource=resourceLoader.getResource("classpath:preferences.json");
    

    In your case, as you need the file you may use following

    File file = resource.getFile()

    Reference:http://frugalisminds.com/spring/load-file-classpath-spring-boot/ As already mentioned in previous answers don't use ResourceUtils it doesn't work after deployment of JAR, this will work in IDE as well as after deployment

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

    i think the problem lies within the space in the folder-name where your project is placed. /home/user/Dev/Java/Java%20Programs/SystemRoutines/target/classes/jsonschema.json

    there is space between Java Programs.Renaming the folder name should make it work

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