码迷,mamicode.com
首页 > 其他好文 > 详细

map持久化类 Properties;对象序列化 ObjectOutputStream

时间:2017-08-05 20:29:36      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:hang   sed   反序列化   height   turn   tor   修改   comm   reader   

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
View Code

 

对象序列化与反序列化

注意 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; 
    }
View Cod

map持久化类 Properties;对象序列化 ObjectOutputStream

标签:hang   sed   反序列化   height   turn   tor   修改   comm   reader   

原文地址:http://www.cnblogs.com/YKang/p/7291189.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!