springboot读取文件,打成jar包后访问不到的解决
springboot读取文件,打成jar包后访问不到
最新开发出现一种情况,springboot打成jar包后读取不到文件,原因是打包之后,文件的虚拟路径是无效的,只能通过流去读取。
文件在resources下
public void test() { List<String> names = new ArrayList<>(); InputStreamReader read = null; try { ClassPathResource resource = new ClassPathResource("name.txt"); InputStream inputStream = resource.getInputStream(); read = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(read); String txt = null; while ((txt = bufferedReader.readLine()) != null) { if (StringUtils.isNotBlank(txt)) { names.add(txt); } } } catch (Exception e) { e.printStackTrace(); } finally { if (read != null) { try { read.close(); } catch (IOException e) { e.printStackTrace(); } } } }
springboot打jar包后台无法访问静态文件夹
1.ResourceUtils
平常我们写spring boot 项目的时候偶尔会在后台用到classpath 底下的文件,一般我们都是这样写的
File file = ResourceUtils.getFile("classpath:static/image/image");
这样情况下本来是没啥问题的。但是用 打jar 包 运行以后就会找不到这个文件。
Resource下的文件是存在于jar这个文件里面,在磁盘上是没有真实路径存在的,它其实是位于jar内部的一个路径。所以通过ResourceUtils.getFile或者this.getClass().getResource("")方法无法正确获取文件。
对于这种情况。有时候会把项目文档放到项目外边,但是这样很容易把这些东西误删除掉。
2.ClassPathResource
ClassPathResource cpr = new ClassPathResource("static/image/image/kpg"); InputStream in = cpr.getInputStream();
3. ResourceLoader
public class ResourceRenderer { public static InputStream resourceLoader(String fileFullPath) throws IOException { ResourceLoader resourceLoader = new DefaultResourceLoader(); return resourceLoader.getResource(fileFullPath).getInputStream(); } }
用法
InputStream in = ResourceRenderer.resourceLoader("classpath:static/image/image");
这样就完美的解决了jar包底下路径无法访问的问题。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
springboot +rabbitmq+redis实现秒杀示例
本文主要介绍了springboot +rabbitmq+redis实现秒杀示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2022-07-07idea resources目录下的application.properties不能自动提示问题
这篇文章主要介绍了idea resources目录下的application.properties不能自动提示问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2023-11-11
最新评论