一、Resources介绍
Resources :获取资源文件的统一接口。
二、Resources接口主要实现类有
- ClassPathResource:获取类路径下的资源文件
- UrlResource:URL对应的资源,根据一个URL地址即可创建
- FileSystemResource:获取文件系统里面的资源
- ServletContextResource:ServletContext封装的资源,用于访问
- ServletContext环境下的资源
- InputStreamResource:针对输入流封装的资源
- ByteArrayResource:针对于字节数封装的资源
三、Resource接口中主要定义有以下方法
- exists():用于判断对应的资源是否真的存在。
- isReadable():用于判断对应资源的内容是否可读。需要注意的是当其结果为true的时候,其内容未必真的可读,但如果返回false,则其内容必定不可读。
- isOpen():用于判断当前资源是否代表一个已打开的输入流,如果结果为true,则表示当前资源的输入流不可多次读取,而且在读取以后需要对它进行关闭,以防止内存泄露。该方法主要针对于InputStreamResource,实现类中只有它的返回结果为true,其他都为false。
- getURL():返回当前资源对应的URL。如果当前资源不能解析为一个URL则会抛出异常。如ByteArrayResource就不能解析为一个URL。
- getFile():返回当前资源对应的File。如果当前资源不能以绝对路径解析为一个File则会抛出异常。如ByteArrayResource就不能解析为一个File。
- getInputStream():获取当前资源代表的输入流,除了InputStreamResource以外,其它Resource实现类每次调用getInputStream()方法都将返回一个全新的InputStream。
四、在bean中获取Resource的方式有以下四种方式
1、直接通过new各种类型的Resource来获取对应的Resource。
/**
* ClassPathResource可以用来获取类路径下的资源
* @throws IOException
*/
@Test
public void testClassPath() throws IOException {
Resource resource = new ClassPathResource("spring-ioc.xml");
String fileName = resource.getDescription();
System.out.println(fileName);
if (resource.isReadable()) {
//每次都会打开一个新的流
InputStream is = resource.getInputStream();
this.printContent(is);
}
}
/**
* FileSystemResource可以用来获取文件系统里面的资源,
* 对于FileSystemResource而言我们可以获取到其对应的输出流OutputStream。
* @throws IOException
*/
@Test
public void testFileSystem() throws IOException {
FileSystemResource resource = new FileSystemResource("D:\\test.txt");