本文共 641 字,大约阅读时间需要 2 分钟。
获取文件路径的代码
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包后,可成功正常运行
转载地址:http://rptvf.baihongyu.com/