Read file from resources folder in Spring Boot

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

提交回复
热议问题