Search code examples
spring-bootresources

Unable to read a file using ResourceLoader


I have a file merge.json in resources directory of my springboot application,which is running in docker.

'jar -tf app.jar' shows BOOT-INF/classes/merge.json in results.

In code I try to read it as:

@Autowired
private ResourceLoader resourceLoader;
....
....
Resource resource = this.resourceLoader.getResource("classpath:merge.json");
File file = resource.getFile();
Files.readString(file.toPath());

But it gives error:

java.io.FileNotFoundException: class path resource [merge.json] cannot be resolved to absolute file path because it does not reside in the file system: jar:nested:/../../app.jar/!BOOT-INF/classes/!/merge.json

What am I missing here?


Solution

  • When your Spring Boot app runs from a JAR file, resources like merge.json are packaged inside the JAR, not as separate files on the file system. That's why calling resource.getFile() doesn't work, because it's trying to find a file on the system, which doesn’t exist in this case.

    To read a file from inside the JAR, you should use an InputStream instead:

    @Autowired
    private ResourceLoader resourceLoader;
    
    Resource resource = this.resourceLoader.getResource("classpath:merge.json");
    try (InputStream inputStream = resource.getInputStream()) {
        String content = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
    }