java十八(对象流序列化)

2017-10-05  本文已影响0人  Nic_ofh

ObjectStream

package File类;

import java.io.*;

public class ObjectStreamDemo {
    public static void main(String[] args) {
        // write();
        read();
    }

    // obj要写入文件,所以要序列化
    public static void write() {
        try {
            Dog dog = new Dog("哈哈", 2);
            File file = new File("obj.txt");
            OutputStream outputStream = new FileOutputStream(file);
            ObjectOutputStream write = new ObjectOutputStream(outputStream);
            write.writeObject(dog);
            write.close();
        } catch (Exception e) {

        }

    }

    // 读取obj文件,所以要反序列化
    public static void read() {
        try {

            File file = new File("obj.txt");

            InputStream in = new FileInputStream(file);
            ObjectInputStream read = new ObjectInputStream(in);
            Dog dog =(Dog)read.readObject();
            System.out.println(dog);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Dog类

package File类;


import java.io.Serializable;

// 对象序列化 Serializable 类
// 1、对象数据用于保存文件就要序列化
// 2、对象数据用于网络传输也要序列化

public class Dog implements Serializable {
    private String name;
    private int age;

    public Dog() {
    }

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

上一篇下一篇

猜你喜欢

热点阅读