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

类的序列化和反序列化(ObjectOutputStream和ObjectInputStream)

时间:2016-10-28 07:48:52      阅读:294      评论:0      收藏:0      [点我收藏+]

标签:ransient   ack   pac   etag   write   new   input   str   puts   

1.需要序列化的类

import java.io.Serializable;
/**
* 必须继承 Serializable 接口才能实现序列化
*/
public class Employee implements Serializable{
    /**
     * transient 关键字表示该字段无法序列化
     */
    private transient int age;
    private String name;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Employee(int age, String name) {
        this.age = age;
        this.name = name;
    }
    
    public Employee() {
    }
    
    @Override
    public String toString() {
        
        return "name:"+this.name+"  age:"+this.age;
    }
}

2.实现序列化

package com.qiao.IOTest;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectInOutTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        write("test6.txt");
        read("test6.txt");
    }
    
    public static void write(String path) throws IOException{
        ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(path)));
        Employee e = new Employee(11, "joey");
        out.writeObject(e);
        out.close();
    }
    
    public static void read(String path) throws IOException, ClassNotFoundException{
        ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(path)));
        Object obj=in.readObject();
        if(null!=obj && obj instanceof Employee){
            Employee e = (Employee)obj;
            System.out.println(e.toString());
        }
    }
    
}

输出:name:joey  age:0

因为age字段被transient关键字修饰,无法序列化,所以获得的值为0,而不是11

 

类的序列化和反序列化(ObjectOutputStream和ObjectInputStream)

标签:ransient   ack   pac   etag   write   new   input   str   puts   

原文地址:http://www.cnblogs.com/Iqiaoxun/p/6006353.html

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