有时候,我们需要从不同位置(例如文件系统,classpath,URL)中读取外部资源,Spring为我们提供了资源装载器提供统一的getResource()方法,按照资源路径对齐外部资源。你可以为路径指定不同的前缀从不同位置加载资源。有三种前缀:从文件系统加载资源,使用file前缀;从classpath加载资源使用classpath前缀;获取网络上的资源使用URL前缀。
方法一:
创建一个类,实现ResourceLoaderAware接口,重写setResourceLoader方法
package com.lkt.entity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
@Component
public class Resource1 implements ResourceLoaderAware {
private ResourceLoader resourceLoader;
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader=resourceLoader;
}
public void getTxt() throws IOException{
Resource banner=resourceLoader.getResource("file:e:\\num.txt");
InputStream in=banner.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in));
while(true){
String line=br.readLine();
if(line==null){
break;
}
System.out.println(line);
}
br.close();
in.close();
}
}
因为使用注解的方式,所以配置文件中就不需要配置东西
调用:
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Resource1 r=(Resource1) ac.getBean("resource1");
try {
r.getTxt();
} catch (IOException e) {
e.printStackTrace();
}
}
就可以打印出num.txt中的内容了
方法二
创建一个类,添加Resource属性,并实现get/set
package com.lkt.entity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
@Component
public class Resource2 {
@Value("file:e:\\num.txt")
private Resource resource;
public Resource getResource() {
return resource;
}
public void setResource(Resource resource) {
this.resource = resource;
}
public void getTxt() throws IOException{
//Resource banner=resourceLoader.getResource("file:e:\\num.txt");
InputStream in=resource.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in));
while(true){
String line=br.readLine();
if(line==null){
break;
}
System.out.println(line);
}
br.close();
in.close();
}
}
调用
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Resource2 r=(Resource2) ac.getBean("resource2");
try {
r.getTxt();
} catch (IOException e) {
e.printStackTrace();
}
}