简体   繁体   中英

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

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.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM