1. 概述
java.util.Properties
继承于Hashtable
,来表示一个持久的属性集。它使用键值结构存储数据,每个键及其对应值都是一个字符串。该类也被许多Java类使用,比如获取系统属性时,System.getProperties
方法就是返回一个Properties
对象。
2 Properties类
构造方法
-
public Properties()
:创建一个空的属性列表。
特有方法
方法名 |
说明 |
Object setProperty(String key, String value) |
设置集合的键和值,都是String类型,底层调用Hashtable方法put. |
String getProperty(String key) |
使用此属性列表中指定的键搜索属性. |
Set<String> stringPropertyNames() |
从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串. |
与流相关的方法
方法名 |
说明 |
void load(InputStream inStream) |
从输入字节流读取属性列表(键和元素对) |
void load(Reader reader) |
从输入字符流读取属性列表(键和元素对) |
void store(OutputStream out, String comments) |
将此属性列表(键和元素对)写入此Properties表中,以适合于使用 load(InputStream)方法的格式写入输出字节流. |
void store(Writer writer, String comments) |
将此属性列表(键和元素对)写入此Properties表中,以适合使用 load(Reader)方法的格式写入输出字符流. |
-
public void load(InputStream inStream)
: 从字节输入流中读取键值对。 -
public void load(Reader reader)
: 从字符输入流中读取键值对。
参数中使用了字节输入流,通过流对象,可以关联到某文件上,这样就能够加载文本中的数据了。文本数据格式:
filename=a.txt
length=209385038
location=D:\a.txt
加载代码演示:
public static void main(String[] args) throws FileNotFoundException {
// 创建属性集对象
Properties pro = new Properties();
// 加载文本中信息到属性集
pro.load(new FileInputStream("read.txt"));
// 遍历集合并打印
Set<String> strings = pro.stringPropertyNames();
for (String key : strings ) {
System.out.println(key+" -- "+pro.getProperty(key));
}
}
- public void store(OutputStream outStream,String comments):把Properties集合对象的键值对保存到文件中
- public void store(Writer writer,String comments):把Properties集合对象的键值对保存到文件中
public static void main(String[] args) throws IOException {
// 创建Properties集合对象
Properties props = new Properties();
// 创建InputStream/Reader的子类对象,绑定源文件
InputStream is = new FileInputStream("day13_sw\\src\\config.properties");
// Properties集合对象调用load方法传递InputStream/Reader的子类对象,
// 把文件内容以键值对的方式加载到Properties集合对象中
props.load(is);
// 遍历集合
Set<String> propertyNames = props.stringPropertyNames();
for (String propertyName : propertyNames) {
String propertyValue = props.getProperty(propertyName);
if("age".equals(propertyName)) {//age属性的值增加10岁
props.setProperty(propertyName,Integer.parseInt(propertyValue)+10+"");
}
}
OutputStream os = new FileOutputStream("day13_sw\\src\\config.properties");
// 把Properties集合对象中的内容存储到文件中
props.store(os,null);
}