Properties是HashTable的一个子类
由于集合是存储在内存中的,IO是可以存到硬盘中,那么Properties是将内存中的集合存入IO的整合
特点:
HashTable的子类,Map集合中的方法都可以用
该集合没有泛型(在Properties后面不用加<泛型类型>),键值对都是字符串
它是一个可持久化的属性集,键值对可以存到集合,也可以存到持久化的硬盘中;键值的来源也可以是持久化的设备
有和流技术相结合的方法:
void load(InputStream inStream)
void load(Reader reader)
void store(OutputStream out, String comments)
void store(Writer writer, String comments)
1. Properties结合存储键值对
1.1 存储方法:Object setProperty(String key, String value)
等同于HashTalbe中的put()方法,双参都是String类型,没有泛型


1.2 获取方法:String getProperty(String key)
等同于HashTable中的get()方法

1.3 获取Properties集合中所有键值:Set<String> stringPropertyNames()
类似于Map接口中的keySet()方法

2. Properties集合的特有功能
2.1. load()方法
load的文件名规则: *.properties
文件中的格式:键=值 键和值用=隔开,且不能有多余空格
2.1.1. 方法
流对象读取文件中的键值对,保存到集合
void load(InputStream inStream) 传递字节输入流
void load(Reader reader) 传递字符输入流
2.1.2. 读取流对象中键值对存入集合Properties
pro.properties文件中存入
name=kluter
age=35
e-mail=kluter@21cn.com
#test=testString
若要屏蔽文件中的某个键值对,在该行之前加#号,将其注释掉

2.2. store()方法
2.2.1. 方法
从集合中读取键值对,以流对象保存到文件中
void store(OutputStream out, String comments) 传递字节输出流
void store(Writer writer, String comments) 传递字符输出流
comments是注释,表明这次写入的目的、时间等等,相当于changLog
2.2.2. 将Properties集合中的键值对存入输出流对象
public static void propertiesLoadStoreDemo() throws IOException{
Properties pro = new Properties();
pro.setProperty("name2", "kluter1");
pro.setProperty("age2", "34");
pro.setProperty("e-mail12", "25942604@qq.com");
pro.store(new FileOutputStream("/kluter/temp/pro.properties"), "for test");
}
结果:

网友评论