介绍
Properties属性集合
特点:
存储属性名和属性值
属性名和属性值都是字符串类型
没有泛型
和流有关
Properties用法
/**
* 创建Properties集合:Properties properties = new Properties();
* 添加数据:properties.setProperty("属性名","属性值");
* 获取数据:System.out.println(properties.getProperty("username"));
* 遍历:1.keySet遍历
* for (Object each:properties.keySet()){
* System.out.println(each + "---" + properties.get(each));
* }
* 2.entrySet遍历
* for (Map.Entry<Object, Object> each:properties.entrySet()){
* System.out.println(each.getKey() + "---" + each.getValue());
* }
* 3.stringPropertyNames遍历
* for (String each: properties.stringPropertyNames()){
* System.out.println(each + "---" + properties.getProperty(each));
* }
*
* 和流有关的方法:
* 1.list方法 输出到文件
* PrintWriter pw = new PrintWriter("E:\\JAVA\\day\\src\\Properties");
* properties.list(pw);
* pw.close();
* 2.store方法(不能存在中文) 输出到文件
* FileOutputStream fos = new FileOutputStream("E:\\JAVA\\day\\src\\Properties\\store.properties");
* properties.store(fos,""); //注释不能是中文
* fos.close();
* 3.load方法 输入到Properties集合中
* Properties properties1 = new Properties();
* FileInputStream fis = new FileInputStream("E:\\JAVA\\day\\src\\Properties\\store.properties");
* properties1.load(fis);
* fis.close();
* System.out.println(properties1.toString());
*
*/
public static void main(String[] args) throws Exception{
Properties properties = new Properties();
properties.setProperty("username","张三");
properties.setProperty("age","21");
System.out.println(properties.toString());
System.out.println(properties.getProperty("username"));
for (Object each:properties.keySet()){
System.out.println(each + "---" + properties.get(each));
}
for (Map.Entry<Object, Object> each:properties.entrySet()){
System.out.println(each.getKey() + "---" + each.getValue());
}
for (String each: properties.stringPropertyNames()){
System.out.println(each + "---" + properties.getProperty(each));
}
PrintWriter pw = new PrintWriter("E:\\JAVA\\day\\src\\Properties\\Print.txt");
properties.list(pw);
pw.close();
FileOutputStream fos = new FileOutputStream("E:\\JAVA\\day\\src\\Properties\\store.properties");
properties.store(fos,"注释");
fos.close();
Properties properties1 = new Properties();
FileInputStream fis = new FileInputStream("E:\\JAVA\\day\\src\\Properties\\store.properties");
properties1.load(fis);
fis.close();
System.out.println(properties1.toString());
}