-
是一个Map体系的集合类(该类继承Hashtable类 ,Hashtable该类实现了Map接口)
-
Properties可以保存到流中或从流中加载
-
属性列表中的每个键及其对应的值都是一个字符串
public class PropertiesDemo01 {
public static void main(String[] args) {
//创建集合对象
// Properties prop = new Properties(); //错误
Properties prop = new Properties();
//存储元素
prop.put("itheima001", "佟丽娅");
prop.put("itheima002", "赵丽颖");
prop.put("itheima003", "刘诗诗");
//遍历集合
Set
2.Properties作为Map集合的特有方法该类拥有Map方法,添加就map方法,put。具体MapJavaMap集合_華同学.的博客-CSDN博客
特有方法
| 方法名 | 说明 |
|---|---|
| Object setProperty(String key, String value) | 设置集合的键和值,都是String类型,底层调用 Hashtable方法 put |
| String getProperty(String key) | 使用此属性列表中指定的键搜索属性 |
| Set | 从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串 |
public class PropertiesDemo02 {
public static void main(String[] args) {
//创建集合对象
Properties prop = new Properties();
//Object setProperty(String key, String value):设置集合的键和值,都是String类型
prop.setProperty("it001", "佟丽娅");
prop.setProperty("it002", "赵丽颖");
prop.setProperty("it003", "刘诗诗");
//String getProperty(String key):使用此属性列表中指定的键搜索属性
// System.out.println(prop.getProperty("it001"));
// System.out.println(prop.getProperty("it0011"));
// System.out.println(prop);
//Set stringPropertyNames():从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串
Set names = prop.stringPropertyNames();
for (String key : names) {
// System.out.println(key);
String value = prop.getProperty(key);
System.out.println(key + "," + value);
}
}
}
3.properties和IO流相结合的方法*****
| 方法名 | 说明 |
|---|---|
| void load(Reader reader) | 从输入字符流读取属性列表(键和元素对) |
| void store(Writer writer, String comments) | 将此属性列表(键和元素对)写入此 Properties表中,以适合使用 load(Reader)方法的格式写入输出字符流 |
要创建properties 类型的文件 进行操作 读取或者写入(写入的情况很少)
配置文件:
xml <开始标签>结束标签>
properties
key=value
key1=value1
yaml
key:value
key1:value1
注:这些配置文件 支持项目运行的一些数据,
读数据:
public class Demo01 {
public static void main(String[] args) throws IOException {
Properties pp = new Properties();
// 加载文件到集合中
// pp.load(new FileInputStream("day12\src\ccc.properties"));
FileReader fr = new FileReader("day12\src\ccc.properties");
pp.load(fr);
// pp.load();
fr.close();
// 获取所有key
Set set = pp.stringPropertyNames();
// 遍历
for (String s : set) {
System.out.println(s + "->" + pp.getProperty(s));
}
}
}
写数据:
public class Demo02 {
public static void main(String[] args) throws IOException {
Properties pp = new Properties();
pp.setProperty("name","张三");
pp.setProperty("age","19");
pp.setProperty("sex","男");
// FileOutputStream fos = new FileOutputStream("day12\src\eee.properties");
FileWriter fw = new FileWriter("day12\src\eee.properties");
// pp.store(fos,"key=value");
// pp.store(fos,null);
pp.store(fw,null);
fw.close();
}
}
pp.store(fw,null); / pp.store(fos,"key=value"); 这里的null 或后面的字符串 是文件上边的注释信息,null就为不写 “key=value”



