ResourceLoader接口的主要作用是进行org.springframework.core.io.ResourceLoader对象实例化,这个接口的定义如下:
读取指定的资源信息:public getResource Resource getResource(String location);
取得类加载器:public getClassLoader ClassLoader getClassLoader()
ResorceLoader是一个接口,于是要使用这个接口必须知道它对应的子类:org.springframework.core.io.DefaultResourceLoader,利用这个子类就可以实现ResourceLoader接口的实例化,但是现在整个资源操作的问题并不在于Resource或者是ResourceLoader接口,以及其一堆的子类,而关键性的问题在于这个定位的字符串,
文件读取资源:"file:路径";
CLASSPATH读取:"claspath:路径";
网络读取:"http://操作路径";
范例:进行文件读取
import java.io.File; import java.io.IOException; import java.util.Scanner; import org.apache.log4j.helpers.Loader; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; public class FileResourceLoader { public static void main(String[] args) throws IOException { ResourceLoader rlLoader=new DefaultResourceLoader(); Resource source=rlLoader.getResource("file:E:"+File.separator+"练习.txt"); System.out.println("数据长度"+source.contentLength()); Scanner scanner=new Scanner(source.getInputStream()); if(scanner.hasNext()){ System.out.println(scanner.next()); } } }
只是写了一个字符串,而后就可以进行读取了
范例:读取CLASSPATH的路径
import java.io.IOException; import java.util.Scanner; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; public class ClassPathResourceLoader { public static void main(String[] args) throws IOException { ResourceLoader rlLoader=new DefaultResourceLoader(); Resource source=rlLoader.getResource("classpath:applicationContext.xml"); System.out.println("数据长度"+source.contentLength()); Scanner scanner=new Scanner(source.getInputStream()); while(scanner.hasNext()){ System.out.println(scanner.next()); } } }
范例:读取网络资源
import java.io.IOException; import java.util.Scanner; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; public class HttpResourceLoader { public static void main(String[] args) throws IOException { ResourceLoader rlLoader=new DefaultResourceLoader(); Resource source=rlLoader.getResource("http://test.testzwb.cn/"); System.out.println("数据长度"+source.contentLength()); Scanner scanner=new Scanner(source.getInputStream()); while(scanner.hasNext()){ System.out.println(scanner.next()); } } }
所有读取的操作过程之中,可以清楚感受到,都是利用了字符串来进行的资源定位,也就是在整个Spring里面核心的设计思想就是:就是利用合理的字符串格式来进行更加复杂的操作,