Tag Archives: java.io.filenotfoundexception

[Solved] Read the resources resource and convert it to file error: java.io.filenotfoundexception

Read the resources resource and convert it to file

Project scenario:

read JSON file from resources directory to get file


Problem Description:

there are no problems in the local project. As a result, an error is reported after the spring boot hits jar

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

Code example:

 Resource resource = new ClassPathResource(PushFcmApnsProperties.androidFilePath);
            FileInputStream serviceAccount = new FileInputStream(resource.getFile());
            

Cause analysis:

in the development and debugging stage, when there is no package, you can locate the resource file through the path. At this time, the resource file really exists in the local disk of the computer </ font>

After packaging, spring attempts to access the file system path, but cannot access the path in the jar. So report an error. At this time, the resource file is in the classes file in the jar package
for example:


Solution:

 

//Change the read method first via
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("relative path");

// Get the inputStream stream of the file and convert it to file to create a temporary file
File bathFile = File.createTempFile("filename", "file format");
            FileUtils.copyInputStreamToFile(inputStream, bathFile);