Read file from resources folder in Spring Boot

后端 未结 12 1136
盖世英雄少女心
盖世英雄少女心 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: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"));
    

提交回复
热议问题