我在读取springboot下templates目录下excel模板的时候,本地测试使用ClassPathResource都可以正常读取,但打包成jar包传到服务器上就无法获取了.
报错信息是:class path resource [xxxx] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:xxxx.jar!/BOOT-INF/classes!xxxx,话不多说,先看正确的获取方法:使用PathMatchingResourcePatternResolver。
//获得文件流,因为在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流。(一定要用流,不要尝试去拿到绝对路径,否则报错!)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | String txt = ""; ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); //Resource[] resources = resolver.getResources("templates/layout/email.html"); Resource resource = resolver.getResource("templates/layout/email.html"); Resource resource = resources[0]; //获得文件流,因为在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流 InputStream stream = resource.getInputStream(); StringBuilder buffer = new StringBuilder(); byte[] bytes = new byte[1024]; try { for (int n; (n = stream.read(bytes)) != -1; ) { buffer.append(new String(bytes, 0, n)); } } catch (IOException e) { e.printStackTrace(); } txt = buffer.toString(); |
到此问题已经解决,想知道根本原因的继续往下看下面链接的内容。
https://www.renfei.net/posts/1003293
因为resourceUrl.getProtocol()不是file,而是 jar,这样就抛出了一个FileNotFoundException异常。
ResouceUtils.getFile()是专门用来加载非压缩和Jar包文件类型的资源,所以它根本不会去尝试加载Jar中的文件,要想加载Jar中的文件,只要用可以读取jar中文件的方式加载即可,比如 xx.class.getClassLoader().getResouceAsStream()这种以流的形式读取文件的方式,所以使用读取文件流就可以拿到了。