Properties是HashTable的子类,可以用map的方法,没有泛型,键值对是字符串
无参构造 Properties()
成员方法
存入 setProperty(String key, String value) // 不用put
取值 getProperty(String key)
写入文件 store(OutputStream out,String comments) // 将集合中的元素储存到文件中
store(Writer w, String comments)
从文件中读取 load(InputStream inStream)
load(Reader reader)
文件中存储 key=value 中间不能有空格,不要多加任何东西 文件后缀 .properties
# 为注释
Properties p = new Properties(); p.setProperty("name", "zhang3"); // put into map p.setProperty("number", "15700"); p.setProperty("age", "23"); // 1 store(OutputStream out, String comments) OutputStream out = new FileOutputStream("E:/test.properties"); p.store(out, "#"); // 2 store(Writer w, String comments) Writer w = new FileWriter("E:/w.properties"); p.store(w,"#"); // 1 load(InputStream inStream) InputStream inStream = new FileInputStream("E:/test.properties"); p.load(inStream); // 2 load(Reader r) Reader r = new FileReader("E:/w.properties"); p.load(r); String age = p.getProperty("age"); // 23
对象序列化与反序列化
注意 1 静态成员变量不能序列化
2 transient 声明的成员变量不能序列化 public transient int age;
3 对象要实现Serializable接口 (标记接口)
4 InvalidClassException 修改源码后没有重新写对象,导致序列号不同,序列号冲突问题
做一个不变的序列号 static final long serialVersioUID = 12154633489663L ,告诉编译器自己有序列号,编译器就不会生成
public static void main(String[] args) throws IOException, ClassNotFoundException{ // People p = new People(); //writeObj(p); People p = (People) readObj("E:/obj.txt"); System.out.println(p.age); } public static void writeObj(Object obj) throws IOException{ OutputStream out = new FileOutputStream("E:/obj.txt"); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(obj); oos.close(); } public static Object readObj(String name) throws IOException, ClassNotFoundException{ InputStream in = new FileInputStream(name); ObjectInputStream ois = new ObjectInputStream(in); Object obj = ois.readObject(); return obj; }