版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jaune161/article/details/51476089
在项目中我们经常需要获取配置文件,有时候会出现在JavaSE项目中获取文件的代码能正常运行,但是到JavaEE项目中就不可以了。针对这种情况我们可以使用Spring提供的Resource工具类
Spring 的优秀工具类盘点,第 1 部分: 文件资源操作和 Web 相关工具类
Spring 的优秀工具类盘点,第 2 部分: 特殊字符转义和方法入参检测工具类
简介
Resource主要是获取资源,Spring提供了很多获取资源的工具类,其中主要有
ClassPathResource
、FileSystemResource
、UrlResource
、ServletContextResource
等工具类。下面我们一一介绍其用途。
ClassPathResource
默认是从项目的根目录获取资源(普通项目为src
,Maven项目为src/main/resources
)。如果指定了相对的类名,则从指定类的相对路径获取资源。
--src/main/resource
|--aop
|--bean
|--lession01
|--lession02
|-applicationContext.xml
|-setup.properties
@Test
public void test() throws Throwable{
ClassPathResource rs= new ClassPathResource("spel/setup.properties");
System.out.println(rs.exists()); //判断文件是否存在
System.out.println(rs.getFilename()); //获取文件名
System.out.println(rs.getPath()); //获取文件的路径(相对路径)
System.out.println(rs.getFile()); //获取文件
System.out.println(rs.getInputStream()); //获取InputStream
}
FileSystemResource
从文件系统中获取资源
@Test
public void testFileSystemResource() throws Exception{
FileSystemResource rs= new FileSystemResource("F:/temp/resource.txt");
System.out.println(rs.exists()); //判断文件是否存在
System.out.println(rs.getFilename()); //获取文件名
System.out.println(rs.getPath()); //获取文件的路径(相对路径)
System.out.println(rs.getFile()); //获取文件
System.out.println(rs.getInputStream()); //获取InputStream
}
UrlResource
从网络获取资源
@Test
public void testUrlResource() throws Exception{
UrlResource rs = new UrlResource("http://www.springframework.org/schema/beans/spring-beans-4.1.xsd");
System.out.println(rs.exists()); //判断文件是否存在
System.out.println(rs.getFilename()); //获取文件名
System.out.println(rs.getInputStream()); //获取InputStream
}
ServletContextResource
获取web根目录下的资源
public void test(HttpServletRequest request) throws IOException{
ServletContextResource rs = new ServletContextResource(
request.getServletContext(),"WEB-INF/springMVC-servlet.xml");
System.out.println(rs.getPath());
System.out.println(rs.getURL());
}