spring读书笔记:resource接口及resourceLoader资源加载器

   由于jdk所提供的资源访问类不能满足各种底层资源访问需求。因此我们大多选择spring的resource接口来解决这类问题,该接口拥有对应不同资源类型的实现类。
    Resource接口主要方法有:
  1.boolean exists() 判断资源是否存在
  2.boolean ipOpen() 判断资源是否打开
  3.URL getURL()throws IOException 如果底层资源可以表示成URL,返回对应URL对象
  4.File getFile() throws IOException 如果底层资源可以表示成文件,返回对应File对象
  5.InputStream getInputStream() throws IOException 返回资源对应的输入流

  Resource具体实现类:
  ClassPathResource:类路径下的资源,位置在classes路径下
  FileSystemResource:文件系统资源,资源以文件系统路径的方式表示,如:D:/File/conf.xml;
  InputStreamResource:对应一个InputStream的资源
  ServletContextResource:访问web容器上下文中资源的类,负责以相对于web应用根目录的路径加载资源,支持以流和URL的方式访问,。
  UrlResource :用户能够访问任何可以通过URL表示的资源。如http资源,ftp资源。
 
  例如:
public class FileSourceExample {

    public static void main(String[] args) {
    try {
String filePath = "D:/classes/conf/file1.txt";
Resource res1 = new FileSystemResource(filePath);
         //转换文件编码格式
         EncodedResource encRes = new EncodedResource(res1,"UTF-8");
     String content  = FileCopyUtils.copyToString(encRes.getReader());
         Resource res2 = new ClassPathResource("conf/file1.txt");
         Resource res3 = new ServletContextResource(application,"/WEB-INF/classes/conf/file1.txt");
         InputStream ins1 = content.getInputStream();
         InputStream ins2 = res2.getInputStream();
         System.out.println("res1:"+encRes.getFilename());
         System.out.println("res2:"+res2.getFilename());           
    } catch (IOException e) {
e.printStackTrace();
}
}
}

资源加载器:ResourceLoader
Spring定义了一套资源加载的接口,并提供了实现类
Resourceloader接口的getResource(String location)方法
ResourcePatternResolver接口,定义新的接口方法:getResources(String locationPattern)
  PathMatchingResourcePatternResolver类

例如:
public class PatternResolverTest {
  public static void main(String[] args) throws Throwable{  ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource resources[] =resolver.getResources("classpath*:com/baobaotao/**/*.xml");
for(Resource resource:resources){
System.out.println(resource.getDescription());
}
}
}

猜你喜欢

转载自lafecat.iteye.com/blog/2042595
今日推荐