【sprint】jar包getFile问题

获取文件路径的代码

File path = null;
try {
    path = new File(ResourceUtils.getURL("classpath:").getPath());
} catch (Exception e) {
    e.printStackTrace();
}

本地调试运行均没有任何问题,打成jar包后部署到服务器上报错FileNotFoundException

使用绝对路径或者使用ResourceUtils.getFile等方式均同样出现以上问题

错误原因:
ResouceUtils.getFile()是专门用来加载非压缩文件类型的资源的,所以它根本不会去读取jar包中的资源,本地之所以没事是因为本地访问的不是jar而是直接编译的

解决方法:
要想读取jar包中的文件,只能通过流来进行读取,可以使用new ClassPathResource(filepath)

代码如下

ClassPathResource resource = new ClassPathResource("");
// 获取文件路径
String path = resource.getURL().getPath();
// 获取文件名称
filename = resource.getFilename();
// 获取文件流
InputStream inputStream = resource.getInputStream();

打成jar包后,可成功正常运行

你可能感兴趣的:(#,java,java,sprint)