spring学习(二):资源访问利器

xiaoxiao2021-02-28  59

1.Resource接口:                     该接口提供了更强的访问底层资源的能力,拥有对应不同资源的类型的实现类;主要方法:                      boolean exists();    资源是否存在;                                boolean isOpen();  资源是否打开;                                URL getURL() throws IOException;  如果底层资源可以表示成URL,该方法返回对应的URL对象;                                File getFile() throws IOException; 如果底层资源对应一个文件,该方法返回对应的File对象;                                InputStream getInputStream() throws IOException; 返回资源对应的输入流;          2.Resource的具体实现类:                               ByteArrayResource: 二进制数组表示的资源,二进制数组资源可以在内存中通过程序构造;        ClassPathResource:类路径下的资源,资源以相对于类路径的方式表示;                            FileSystemResource:   文件系统资源,资源以文件路径的方式表示;                               InputStreamResource:对应一个InputStream资源;                               ServletContextResource:负责行对于Web应用根目录的路径加载资源;                              URLResource:封装了java.net.URL,它使用户能够访问任何通过URL表示的资源,如文件系统资源、HTTP资源、FTP资源;   package mainTest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; public class ResourceTest { public static void main(String[] args) { String filePath="D:/workspace/springLearn/src/config/file1.txt"; //1.使用文件系统路径访问; //Resource res1= new FileSystemResource(filePath); //2.使用类路径加载文件 Resource res1=new ClassPathResource("config/file1.txt"); InputStream ins1=null; try { ins1 = res1.getInputStream(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } BufferedReader reader =new BufferedReader(new InputStreamReader(ins1)); StringBuilder sb=new StringBuilder(); String line=null; try { while((line=reader.readLine())!=null){ sb.append(line); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(sb); } }   3.资源加载: 为访问不同类型的资源,必须使用相同的Resource实现类,这比较麻烦;所以Spring提供了一个强大的加载资源机制,不仅能通过“classPath:”、“file:”等资源地址前缀识别不同的资源类型,还支持Ant风格带通配符的资源地址; classpath: 从类路径中加载资源,classpath:和classpath/是等价的,都是相对于类的根路径。资源文件可以在标准的文件系统中,也可以在jar或者zip中;classpath:只会加载一个相应文件;classpath*:会扫描所有的文件; file: 使用UrlResource从文件系统目录中装载资源,可以是绝对或相对路径; http:// 采用UrlResource从web服务器中装载资源; ftp:// 采用UrlResource从FTP服务器中装载资源; 无前缀 根据ApplicationContext具体实现类采用对应的resource; 4.资源加载器: ResourceLoader 接口仅有一个getResource(String location)方法,可以根据一个资源地址加载文件资源; ResourcrPatternResolver扩展RwsourceLoader接口,定义了一个新的接口方法:getResources(String locationPattern),该方法支持带资源前缀及Ant风格的资源路径表达式; PathMatchingResourcePatternResolver是Spring提供了标准实现类;
转载请注明原文地址: https://www.6miu.com/read-56136.html

最新回复(0)