Properties
- 继承了
Hashtable
,它是一个map映射 - Properties类表示了一个持久的属性集
- Properties可保存在流中或者从流中加载
-
构造方法
Properties()
:创建一个无默认值的空属性列表
-
特有方法:
String getProperty(String key)
: 用指定的键在此属性列表中搜索属性(只能是字符串类型)— 对应get()
Object setProperty(String key, String value)
: 调用 Hashtable 的方法 put(只能是字符串类型)— 对应put()
void store(OutputStream out, String comments)
: 将此 Properties 键值对写入字节输出流void store(Writer writer, String comments)
: 将此 Properties 键值对写入字符输出流void load(InputStream inStream)
: 从输入流中读取属性列表(键值对)void load(Reader reader)
: 按简单的面向行的格式从输入字符流中读取属性列表(键值对)
public class PropertiesDemo { public static void main(String[] args) throws IOException { // 创建Properties对象 Properties properties = new Properties(); // 添加元素 setProperty() key, value 均为字符串类型 properties.setProperty("001","lili"); properties.setProperty("002","Sam"); properties.setProperty("003","Potter"); System.out.println(properties); // {001=lili, 002=Sam, 003=Potter} // 获取某个key对应的元素值 String value = properties.getProperty("003"); System.out.println(value); // Potter // 将properties键值对输出到一个文件中 FileOutputStream out = new FileOutputStream(".\\Day22\\pro.txt"); // 将properties中的键值对持久化存储 // 第二个参数comments用于添加文件的说明 properties.store(out, null); // 关流 out.close(); Properties properties1 = new Properties(); // 将文件中的内容读取到properties中 FileInputStream in = new FileInputStream(".\\Day22\\pro.txt"); // 调用加载方法 properties1.load(in); // 关流 in.close(); // 输出properties中的数据 System.out.println(properties1); // {001=lili, 002=Sam, 003=Potter} } }