1.Properties类
概述:java.util.Properties类 继承于 Hashtable
特点:
1.Properties当成Map集合使用,键和值的类型为Object类型
2.Properties当成属性集是使用,键和值的类型为String类型
构造方法:
- public Properties():创建一个空的属性列表
成员方法:
- public synchronized Object setProperty(String key, String value):保存一对键值对
- public Set<String> stringPropertyNames():获取所有的键的名称,返回set<String>集合
- public String getProperty(String key):使用此属性列表中指定的键可以搜索获取对象的属性值
- public synchronized void load(InputStream inStream):从字节输入流中读取键值对
- public synchronized void load(Reader reader):从字符输入流中读取键值对
注意:
文本文档中,文本中的数据,必须是键值对的形式,可以使用空格、等号、冒号等符号分隔
public class Tests {
public static void main(String[] args) throws IOException {
// 1.创建Properties对象
Properties p = new Properties();
// 2.存储键值对
p.setProperty("张三","24");
p.setProperty("李四","12");
p.setProperty("王五","14");
p.setProperty("赵六","21");
// 3.获取所有的键
Set<String> keys = p.stringPropertyNames();
// 4.根据键找指,并依次输出
for (String key : keys) {
String value = p.getProperty(key);
System.out.println(key+","+value);
}
/*
* 需求:把day13路径下的b.txt文本文档中的数据读取到Properties对象中,然后在打印出来
* */
// 1.创建字节输入流对象,关联b.txt
//FileInputStream fis = new FileInputStream(str);
FileReader fr = new FileReader(str);
// 2.properties对象 加载文件中的数据
p.load(fr);
// 3.关闭流
fr.close();
// 4.打印信息
System.out.println(p);
}
static String str = "day13_Properies类&缓冲流&转换流&序列化流&装饰者模式&commons-io工具包\\resources\\b.txt";
}
2、扩展Properties开发中的使用
Properties在开发中的实际应用:
1.开发中的配置文件一般都是后缀为.properties的文件
2.开发中的配置文件一般都是放于src目录下
3.开发中,配置文件的内容一般不会出现中文
4.开发中,一般只会去配置文件中读取数据
成员方法:
- public void store(OutputStream out, String comments):把Properties对象中的键值对信息,写回到配置文件中
- comments:评论
- public void store(Writer writer, String comments):把Properties对象中的键值对信息,写回到配置文件中
- public synchronized void load(InputStream inStream):从字节输入流中
- public synchronized void load(Reader reader):从字符输入流中读取键值对
public class Tests {
public static void main(String[] args) throws IOException {
// 1.创建Properties对象
Properties p = new Properties();
// 2。调用load方法加载配置文件
p.load(new FileInputStream(str));
// 3.获取所有的键
Set<String> keys = p.stringPropertyNames();
// 4.根据键找值,并依次输出
for (String key : keys) {
String value = p.getProperty(key);
System.out.println(key+":"+value);
}
System.out.println("=========================扩展:添加一个键值对信息到配置文件中===========================");
// 1.往Properties对象中添加一个键值对信息
p.setProperty("className","classLoader");
// 2.把Properties对象中所有的键值对重新写回data.properties文件中
p.store(new FileOutputStream(str),"zhangsan");
System.out.println("=========================扩展:修改一个键值对信息到配置文件中===========================");
// 1.往Properties对象中添加一个键值对信息
p.setProperty("username","xiaoming");
p.setProperty("username","sdsng");
// 2.把Properties对象中所有的键值对重新写回data.properties文件中
p.store(new FileOutputStream(str),"lisi");
}
static String str = "day13_Properies类&缓冲流&转换流&序列化流&装饰者模式&commons-io工具包\\resources\\data.properties";
}