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

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

转载于:https://www.cnblogs.com/YKang/p/7291189.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值