Java-对象输入输出(字节流)

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class objectInOutDemo {
    public static void main(String[] args) {
// writeObj();
        readObj();
    }
    private static void readObj() {
        try {
            ObjectInputStream in=new ObjectInputStream(new FileInputStream("person.dat"));
            while (true) {
                Person p = (Person)in.readObject();
                System.out.println(p);
            }
        }  catch (EOFException e) {//通过异常来判断文件读取到结尾
            System.out.println("文件读取完毕!");
        } catch (Exception e) {//
        e.printStackTrace();
    }
    }
    public static void writeObj() {
        Person p1=new Person("Jack",22);
        Person p2=new Person("Rose",21);
        try {
            ObjectOutputStream out =new ObjectOutputStream(new FileOutputStream("person.dat"));
            out.writeObject(p1);
            out.writeObject(p2);
        }  catch (IOException e) {
            e.printStackTrace();
        }
    }
}
//要被写入对象流的类,必须实现Serializable接口----贴标签技术(接口中没有抽象方法,只是为了标识一下)
class Person implements Serializable{//贴标签,判断是Serializable否是类型,可以序列化。可以被写入读出
    private String name;
    private int age;
    public Person(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;
    }
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

运行结果:
Java-对象输入输出(字节流)_第1张图片
Java-对象输入输出(字节流)_第2张图片

你可能感兴趣的:(Java-对象输入输出(字节流))