1、问题现象:项目打成jar包后,使用ResourceUtils.getFile(keystoreFile)
无法访问到资源文件
//classpath为resources目录下
String testFile = "classpath:test.txt";
FileInputStream in = new FileInputStream(ResourceUtils.getFile(testFile));
2、问题分析:项目构建成jar包后,resources目录中的文件并不是直接存在系统中,而是嵌套在jar文件中。
3、解决方法:首先使用resource.getInputStream()
获取到该文件的InputStream
,然后使用FileUtils
的copyToFile()
方法将流拷贝到目标文件中
//要导入的包
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.apache.commons.io.FileUtils;
import java.security.KeyStore;
//测试文件
String testFile = "classpath:test.txt";
//获取test.txt,filePath为文件的绝对路径
String filePath = "D:\\Project\\y_project-RuoYi-master\\RuoYi\\ruoyi-admin\\src\\main\\resources\\test.txt";
//获取资源文件
Resource resource = new ClassPathResource(testFile);
File clientFile = new File(filePath);
FileUtils.copyToFile(resource.getInputStream(), clientFile);
//文件流读取
FileInputStream fileInputStream = new FileInputStream(clientFile);
参考链接:class path resource cannot be resolved to absolute file path