在开发过程中常常会需要读取resources目录下的配置文件,大部分是框架帮我们自动读取,如果我们手动读取该如何读取呢?
以下是个人总结的读取properties文件的三种方式:
username=张无忌
age=18
position=明教第34代教主
education=武当大学太极训练班
address=光明顶
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
<!--IOC相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
</dependencies>
/**
* 基于InputStream读取配置文件
*/
public class PropertiesTest1 {
private InputStream is;
@Test
public void proRead(){
try {
//创建Properties对象
Properties pro = new Properties();
is = PropertiesTest1.class.getResourceAsStream("/data.properties");
//处理中文乱码
pro.load(is);
Set<Map.Entry<Object, Object>> entries = pro.entrySet();
for (Map.Entry<Object, Object> entry : entries) {
String value =(String)entry.getValue();
value = URLEncoder.encode(value, "ISO-8859-1");
value = URLDecoder.decode(value, "GBK");
System.out.println(entry.getKey()+"------"+value);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 通过Spring中的PropertiesLoaderUtils工具类进行获取
*/
public class PropertiesTest2 {
@Test
public void proRead(){
try {
Properties pro = PropertiesLoaderUtils.loadAllProperties("data.properties");
Set<Map.Entry<Object, Object>> entries = pro.entrySet();
for (Map.Entry<Object, Object> entry : entries) {
String value =(String)entry.getValue();
value = URLEncoder.encode(value, "ISO-8859-1");
value = URLDecoder.decode(value, "GBK");
System.out.println(entry.getKey()+"------"+value);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 通过 java.util.ResourceBundle 类读取
*/
public class PropertiesTest3 {
@Test
public void proRead(){
ResourceBundle resourceBundle = ResourceBundle.getBundle("data");
//遍历取值
Enumeration enumeration = resourceBundle.getKeys();
while (enumeration.hasMoreElements()) {
try {
String key = (String) enumeration.nextElement();
String value = resourceBundle.getString(key);
value = URLEncoder.encode(value, "ISO-8859-1");
value = URLDecoder.decode(value, "GBK");
System.out.println(key+"------"+value);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |