1、概述
Properties类型,用来表示Java中properties的持久化集合,可以通过流的形式加载,也可以保存为流的形式
- 每一项的key和value在property列表中都是String类型
- 一个property列表可以包含另外一个property列表作为默认值,当一个key在本列表中找不到就找第二个属性列表
- Properties是线程安全的,因为它继承自HashTable
2、基本方法
- 1、Object setProperty(String key,String value) : 调用父类(HashTable)的 put() 方法
@Test
public void testproperty01(){
Properties prop = new Properties();
prop.setProperty("height","180");
prop.put("width","200");
// value会被强制转型为String类型
prop.put("width",45);
// key值相同会被覆盖
System.out.println("" + prop); // output:{height=180, width=45}
}
- 2、void load(InputStream is):从字符流读取属性列表(key=value)
- 3、void list(PrintStream out):把属性列表输出到指定输出流
- 4、void store(OutputStream out, String comments):把属性列表存储到指定文件,可以加上注释
- 注意:上述输入输出流可以替换为读写器
@Test
public void testproperty02() throws Exception {
int i = 0;
Properties prop = new Properties();
// 获取属性列表文件路径
File dir = new File("properties");
// 遍历属性列表所在路径,找出后缀为'.properties'的全部文件
for(File f: dir.listFiles()){
if(f.isFile() && f.getName().endsWith(".properties")){
// 创建文件输入流,继承自InputStream
FileInputStream fis = new FileInputStream(f);
// 创建文件写入流
//FileWriter fw = new FileWriter("output" + i++ + ".properties");
// 创建文件输出流
FileOutputStream fos = new FileOutputStream("output" + i++ + ".properties");
// 加载属性文件
prop.load(fis);
// 把属性列表内容写入系统输出流
prop.list(System.out);
// Peoperty列表存入文件
prop.store(fos,"myProperties");
}
}
}
3、总结
Properties一般用于加载自定义配置文件。