Spring(1)——文件资源操作

来源:互联网 发布:淘宝运营主管岗位职责 编辑:程序博客网 时间:2024/05/21 23:10

加载文件资源

    Spring 定义了一个 org.springframework.core.io.Resource 接口,Resource 接口是为了统一各种类型不同的资源而定义的,Spring 提供了若干 Resource 接口的实现类,这些实现类可以轻松地加载不同类型的底层资源,并提供了获取文件名、URL 地址以及资源内容的操作方法。

访问文件资源

假设有一个文件地位于 Web 应用的类路径下,您可以通过以下方式对这个文件资源进行访问:

  • 通过 FileSystemResource 以文件系统绝对路径的方式进行访问;
  • 通过 ClassPathResource 以类路径的方式进行访问;
  • 通过 ServletContextResource 以相对于 Web 应用根目录的方式进行访问。
  • 通过 UrlResource 访问远程服务器(web和ftp)上的资源
public static void main(String[] args) {         try {             String filePath =             "D:/masterSpring/chapter23/webapp/WEB-INF/classes/conf/file1.txt";             // ①使用系统文件路径方式加载文件            Resource res1 = new FileSystemResource(filePath);             // ②使用类路径方式加载文件            Resource res2 = new ClassPathResource("conf/file1.txt");           Resource res3 = new ServletContextResource(application,         "/WEB-INF/classes/conf/file1.txt");            InputStream ins1 = res1.getInputStream();             InputStream ins2 = res2.getInputStream();             System.out.println("res1:"+res1.getFilename());             System.out.println("res2:"+res2.getFilename());         } catch (IOException e) {             e.printStackTrace();         } }


 

本地化文件资源

    Spring 提供的 LocalizedResourceHelper 允许通过文件资源基名和本地化实体获取匹配的本地化文件资源并以 Resource 对象返回。假设在类路径的 i18n 目录下,拥有一组基名为 message 的本地化文件资源,我们通过以下实例演示获取对应中国大陆和美国的本地化文件资源:

public class LocaleResourceTest {     public static void main(String[] args) {         LocalizedResourceHelper lrHalper = new LocalizedResourceHelper();         // ① 获取对应美国的本地化文件资源        Resource msg_us = lrHalper.findLocalizedResource("i18n/message", ".properties",         Locale.US);         // ② 获取对应中国大陆的本地化文件资源        Resource msg_cn = lrHalper.findLocalizedResource("i18n/message", ".properties",         Locale.CHINA);         System.out.println("fileName(us):"+msg_us.getFilename());         System.out.println("fileName(cn):"+msg_cn.getFilename());     }  } 


 

Properties文件操作

Spring 提供的 PropertiesLoaderUtils允许您直接通过基于类路径的文件地址加载属性资源,此外,PropertiesLoaderUtils还可以直接从 Resource 对象中加载属性资源。实例:

  
Properties props = PropertiesLoaderUtils.loadAllProperties("jdbc.properties");         System.out.println(props.getProperty("jdbc.driverClassName")); 

特殊编码的资源

        如果字符类型的资源文件需要采用编码如 UTF-8,则在读取资源时必须事先通过EncodedResource制定编码格式,否则会产生中文乱码,如下:

          public static void main(String[] args) throws Throwable  {             Resource res = new ClassPathResource("conf/file1.txt");             // ① 指定文件资源对应的编码格式(UTF-8)            EncodedResource encRes = new EncodedResource(res,"UTF-8");             // ② 这样才能正确读取文件的内容,而不会出现乱码            String content  = FileCopyUtils.copyToString(encRes.getReader());             System.out.println(content);      }         


    EncodedResource 拥有一个 getResource() 方法获取 Resource,但该方法返回的是通过构造函数传入的原 Resource 对象,所以必须通过 EncodedResource#getReader() 获取应用编码后的 Reader 对象,然后再通过该 Reader 读取文件的内容。

原创粉丝点击