源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Spring Boot 读取静态资源文件的方法

  • 时间:2020-08-14 22:41 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Spring Boot 读取静态资源文件的方法
[b]一、需求场景[/b] 有时候我们需要在项目中使用一些静态资源文件,比如城市信息文件 countries.xml,在项目启动后读取其中的数据并初始化写进数据库中。 [b]二、实现[/b] 静态资源文件 countries.xml 放在 src/main/resources 目录下 使用 Spring 的 [url=https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/io/ClassPathResource.html]ClassPathResource [/url]来实现 :
Resource resource = new ClassPathResource("countries.xml");
File file = resource.getFile();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
ClassPathResource 类的注释如下: Resource implementation for class path resources. Uses either a given ClassLoader or a given Class for loading resources. Supports resolution as java.io.File if the class path resource resides in the file system, but not for resources in a JAR. Always supports resolution as URL. 翻译过来就是: 类路径资源的资源实现。使用给定的ClassLoader或给定的类来加载资源。 如果类路径资源驻留在文件系统中,则支持解析为 java.io.File,如果是JAR中的资源则不支持。始终支持解析为URL。 [b]三、Jar 中资源文件[/b] 上面也提到了,如果静态资源文件在文件系统里,则支持解析为 java.io.File,程序是能正常工作的。 到项目打包成 Jar 包放到服务器上运行就报找不到资源的错误了! 解决法案是:不获取 java.io.File 对象,而是直接获取输入流:
Resource resource = new ClassPathResource("countries.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
说明:构造得到 resource 对象之后直接获取其输入流 resource.getInputStream()。 [b]四、附录[/b] [list] [*][url=http://stackoverflow.com/questions/36371748/spring-boot-access-static-resources-missing-scr-main-resources]Spring Boot access static resources missing scr/main/resources[/url][/*] [*][url=https://stackoverflow.com/questions/25869428/classpath-resource-not-found-when-running-as-jar]Classpath resource not found when running as jar[/url][/*] [/list] 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部