Home > database >  java.io.FileNotFoundException: class path resource cannot be opened because it does not exist
java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

Time:01-04

I create a streamHelper function to load any file that is on the classpath, this is the path for my json file, but I got error when I using this function

streamHelper("/Users/my/IdeaProjects/rules-management/data_tacos-sample/post-migration/sourceData/config_-e48059402bd4.json")

java.io.FileNotFoundException: class path resource [/Users/my/IdeaProjects/rules-management/data_tacos-sample/post-migration/sourceData/config_-e48059402bd4.json] cannot be opened because it does not exist
private InputStream streamHelper(String resourcePath) {
    DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
    Resource resource = resourceLoader.getResource(resourcePath);
    return resource.getInputStream();
}

I print the file name on console, when I click that link it can direct me to the file which means the path is good, why I got this error? How to fix that.

CodePudding user response:

The DefaultResourceLoader is a Spring class. According to Spring docs, the DefaultResourceLoader

Will return a UrlResource if the location value is a URL, and a ClassPathResource if it is a non-URL path or a "classpath:" pseudo-URL.

By default, Spring looks for all your resources in a folder called resources.

By default, this handler serves static content from any of the /static, /public, /resources, and /META-INF/resources directories that are on the classpath. Since src/main/resources is typically on the classpath by default, we can place any of these directories there.

Move your json into a folder called resources, make sure that folder is on your classpath, and then call the streamHelper as follows:

streamHelper("classpath:config_-e48059402bd4.json")
  • Related