Properties的特点:
存储属性名与属性值
属性名与属性值都是字符串类型
不存在泛型
该集合与流有关。可保存在流中或者从流中加载,属性列表中每个键及其对应的值都是一个字符串。
demo:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class PropertiesCollection {
public static void main(String[] args) {
PropertiesDemo1();
}
public static void PropertiesDemo1() {
// 创建集合
Properties properties = new Properties();
// 添加数据
properties.setProperty("user_name :", "张三分");
properties.setProperty("age :", "16");
System.out.println(properties);
// 遍历
System.out.println("~~~~~~~~~~~~~key set~~~~~~~~~~~");
Set<Object> proSet = properties.keySet();
for(Object set : proSet) {
System.out.println(set + " " + properties.get(set));
}
System.out.println("~~~~~~~~~~~~~entry set~~~~~~~~~~~");
Set<Map.Entry<Object, Object>> entries = properties.entrySet();
for (Map.Entry<Object, Object> entry : entries) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
System.out.println("~~~~~~~~~~~~~string property names~~~~~~~~~~~");
Set<String> proName = properties.stringPropertyNames();
for (String s:proName) {
System.out.println(s + " " + properties.getProperty(s));
}
// 和流一起使用
System.out.println("~~~~~~~list方法保存数据到文件~~~~~~~");
try {
PrintWriter pw = new PrintWriter("D:\\IntelliJ IDEA\\project\\PropertiesCollection\\src\\main\\java\\test.txt");
properties.list(pw);
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("~~~~~~~~~~~store方法保存数据到文件~~~~~~~~~~~");
try {
FileOutputStream fos = new FileOutputStream("D:\\IntelliJ IDEA\\project\\PropertiesCollection\\src\\main\\java\\test.properties");
properties.store(fos, "annotation");
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("~~~~~~~~~load方法从文件中加载数据~~~~~~~~");
Properties properties1 = new Properties();
try {
FileInputStream fis = new FileInputStream("D:\\IntelliJ IDEA\\project\\PropertiesCollection\\src\\main\\java\\test.properties");
properties1.load(fis);
fis.close();
System.out.println(properties1);
} catch (Exception e) {
e.printStackTrace();
}
}
}