Article Directory
Problem scenario
After springboot is packaged, read the content of the resource file and report an error. The error message is as follows:
cannot be resolved to absolute file path because it does not reside in the file system: jar
Problem environment
software | version |
---|---|
springboot | 2.1.1.RELEASE |
problem causes
After packaging, Spring cannot access the files in the jar package in the form of File.
solution
There are two options:
1. Use resource.getInputStream() to read file content
2. Cache to a temporary file, use the temporary file path for reading
The sample code is as follows:
String tempPath = System.getProperty("java.io.tmpdir")+"tomcat_"+System.currentTimeMillis();
String tempFile = tempPath+File.separator+fileName;
Resource resource = new DefaultResourceLoader().getResource("classpath:META-INF/resources"+filePath);
if (resource == null) {
return "";
}
File file = new File(tempPath);
if (!file.exists()) {
file.mkdir();
}
IOUtil.cp(resource.getInputStream(),new FileOutputStream(new File(tempFile)));
result
Solve the problem smoothly! ! !
to sum up
Life-long learning!
Ask for praise
If my article is helpful to everyone, you can click like or favorite at the bottom of the article;
if there is a good discussion, you can leave a message;
if you want to continue to view my future articles, you can click Follow
You can scan the following QR code to follow me 'S public account: Fengye Zhixuege, check out my latest share!