spring 通过配置读取文本文件

package com.zdc;


import java.io.BufferedReader;
import java.io.InputStreamReader;


import org.springframework.core.io.Resource;


public class FileResource {


// 定义spring的资源路径对象
private Resource resource;


// 文本编码格式
private String charSet;


public void setResource(Resource resource) {
this.resource = resource;
}


public void setCharSet(String charSet) {
this.charSet = charSet;
}


public void getFile() throws Exception {


BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), charSet));
String line = null;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
}

}

 

 

spring xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


<bean id="resource" class="com.zdc.FileResource">
<!-- <property name="resource" value="classpath:file.txt"></property>  类路径下的文本 -->
<!-- <property name="resource" value="file//D:/file.txt"></property>  本地盘下的文本 (编码格式gbk)-->
<!-- <property name="resource" value="http://www.baidu.com"></property>  网上的下载路径 -->
<property name="resource" value="classpath:file.txt"></property>
<property name="charSet" value="UTF-8"></property>
</bean>

</beans>

 

测试:

文本位置:

spring 通过配置读取文本文件

############################################################################################

spring 通过配置读取文本文件