Spring 读取资源
2024-09-01 06:10:32
- Spring 读取资源
- 主要介绍3种方式(当然不止三种,但是这三种基本能应付大多需求)
FileSystemResource:以文件的绝对路径方式进行访问
ClassPathResourcee:以类路径的方式访问
ServletContextResource:web应用根目录的方式访问 - 主要公用方法介绍(Resource接口下的)
getFilename() : 获得文件名称
contentLength() : 获得文件大小
createRelative(path) : 在资源的相对地址上创建新文件
exists() : 是否存在
getFile() : 获得Java提供的File 对象
getInputStream() : 获得文件的流 - 与常规的对应方法
FileSystemResource 效果类似于Java中的File
ClassPathResource 效果类似于this.getClass().getResource("/").getPath();
ServletContextResource 效果类似于request.getServletContext().getRealPath("");
- 主要介绍3种方式(当然不止三种,但是这三种基本能应付大多需求)
场景:
读取Resource下export文件夹中的xml配置文件
1.ClassPathResource
Resource resource = new ClassPathResource("export/config.xml");
File file = resource.getFile(); System.out.println("对应的以往的实现方式:"+this.getClass().getResource("/").getPath());
2.FileSystemResource
FileSystemResource res1=new FileSystemResource("D:/abc.txt");
File f = res1.getFile(); //转换成Java的File对象
ClassPathResource类的注释:
* Supports resolution as {@code 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.
Spring 读取资源文件后如果使用getFile()方法获取的话要保证资源文件是在文件系统中(能正确读取出文件路径)
如果运行的Jar包读出的路径是:app.jar!/BOOT-INF!/classes/.....这个样子
最新文章
- 使用ASP.NET MVC局部视图避免JS拼接HTML,编写易于维护的HTML页面
- Junit基础整理
- D:Balanced Lineup
- 记录一个bug -- sprintf
- POJ2222+暴力搜索
- HTTP状态码搜集
- SQL函数介绍
- jQuery.sort对DOM元素进行排序
- 老李分享:接电话之uiautomator 1
- Linux配置LNMP环境(一)配置Nginx
- c#实现服务端webSocket
- BZOJ 1119: [POI2009]SLO [置换群]
- js定义数组的方法
- 走进Java Map家族 (1) - HashMap实现原理分析
- windows许可证即将过期
- ☆ [POI2007] ZAP-Queries 「莫比乌斯反演」
- linux 内核代码结构
- 中位数&;贪心
- Ice简介+Qt代码示例
- Docker技术入门与实战 第二版-学习笔记-3-Dockerfile 指令详解