下面首先按照传统开发实现一些 基本资源读取
1.读取内存资源
org.springframework.core.io.ByteArrayResource
构造方法:public ByteArrayResource(byte[] byteArray);
范例:实现内存读取
package cn.resource.demo;
import java.io.IOException;
import java.util.Scanner;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
public class ByteResource {
public static void main(String[] args) throws IOException {
//此处的内存处理流与之前讲解的ByteArrayInputStream使用形式类似;
Resource source=new ByteArrayResource("HELLOWORLDE".getBytes());
//单单就可以取得更多的资源信息来讲,这一点比InputStream要强,
System.out.println("数据长度"+source.contentLength());
//如果给出的是InputStream,那么可以利用Scanner简化读取
//getInputStream是通过InputStreamSource父接口继承而来的,
Scanner scanner=new Scanner(source.getInputStream());
if(scanner.hasNext()){
System.out.println(scanner.next());
}
}
}
2.文件读取:org.springframework.core.io.FileSystemResource
构造方法:public FileSystemResource(File file)
构造方法:public FileSystemResource(String path)
范例:进行文件的读取
package cn.resource.demo;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public class FileResource {
public static void main(String[] args) throws IOException {
Resource source=new FileSystemResource(new File("E:"+File.separator+"练习.txt"));
System.out.println("数据长度"+source.contentLength());
Scanner scanner=new Scanner(source.getInputStream());
if(scanner.hasNext()){
System.out.println(scanner.next());
}
}
}
3.CLASSPATH读取:org.springframework.core.io.ClassPathResource
构造方法:poublic ClassPathResource(String path)
只要是保存在CLASSPATH环境下的路径信息都可以通过此类信息读取进来.
范例:读取applicationContext.xml文件
package cn.resource.demo;
import java.io.IOException;
import java.util.Scanner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class CPResource2 {
public static void main(String[] args) throws IOException {
Resource source=new ClassPathResource("applicationContext.xml");
System.out.println("数据长度"+source.contentLength());
Scanner scanner=new Scanner(source.getInputStream());
scanner.useDelimiter("\n");
while(scanner.hasNext()){
System.out.println(scanner.next());
}
}
}
如果要进行文件的读取,必须要提供有完整的路径,也就是所默认的情况下要想读取一个指定的资源,那么必须要想办法拼凑出路径(还需要取得一堆的系统属性).