14、Spring工具类之Resource

在项目中我们经常需要获取配置文件,有时候会出现在JavaSE项目中获取文件的代码能正常运行,但是到JavaEE项目中就不可以了。针对这种情况我们可以使用Spring提供的Resource工具类

Spring 的优秀工具类盘点,第 1 部分: 文件资源操作和 Web 相关工具类
Spring 的优秀工具类盘点,第 2 部分: 特殊字符转义和方法入参检测工具类

简介

Resource主要是获取资源,Spring提供了很多获取资源的工具类,其中主要有ClassPathResourceFileSystemResourceUrlResourceServletContextResource等工具类。下面我们一一介绍其用途。

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());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大扑棱蛾子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值