Java学习笔记之--------IO流之对象处理流

对象处理流

输入流:ObjectInputStream  readObject(反序列化)

输出流:ObjectOutputStream  writeObject(序列化)

注意:

(1) 先序列化后反序列化,反序列化顺序必须与序列化一致。

(2) 不是所有的对象都可以序列化,实现了java.io.Serializable接口的才可以。也不是所有的属性都需要序列化,用transient关键字标记的成员变量不参与序列化过程。

下面为Demo:

public class Employee implements Serializable{

    //transient修饰表示不需要序列化
    private transient String name;
    private double salary;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public Employee() {
    }

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }
}
public class ObjectDemo01 {

    public static void main(String[] args) {
        try {
            seri("d:/xp/test/ser.txt");
            read("d:/xp/test/ser.txt");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 序列化
     * @param destPath
     * @throws IOException
     */
    public static void seri(String destPath) throws IOException{

        Employee emp = new Employee("bjsxt", 1000);
        int arr[] = {1,2,3,4};
        //创建源
        File dest = new File(destPath);
        //选择流
        ObjectOutputStream dos = new ObjectOutputStream(
                new BufferedOutputStream(
                        new FileOutputStream(dest)
                )
        );
        //操作,这里写出的顺序为读取做准备
        dos.writeObject(emp);
        dos.writeObject(arr);
        //释放资源
        dos.close();
    }

    public static void read(String destPath) throws IOException, ClassNotFoundException {
        File src = new File(destPath);
        //选择流
        ObjectInputStream dis = new ObjectInputStream(
                new BufferedInputStream(
                        new FileInputStream(src)
                )
        );
        //操作,读取的顺序与写出一致,必须存在才能读取。数据不一致会导致读出不正确。
        Object obj = dis.readObject();
        if (obj instanceof Employee){
            Employee emp = (Employee)obj;
            System.out.println(emp.getName());
            System.out.println(emp.getSalary());
        }

        obj = dis.readObject();
        int[] arr = (int[]) obj;
        System.out.println(Arrays.toString(arr));

        dis.close();
    }

}

我们可以看到ser.txt如下:

我们无法读取文件中的内容,但是程序可以读取,上面程序的执行结果为:

我们可以看到,输出的第一行为null,因为Employee中的name用transient修饰表示不需要序列化,所以我们也获取不到name的值。

猜你喜欢

转载自blog.csdn.net/wangruoao/article/details/83994672
今日推荐