ObjectOutputStream

public class Test {

    public static void main(String[] args) throws Exception {

         //writeObject();
        readObject();
    }

    private static void readObject() throws Exception {
        FileInputStream fis = new FileInputStream("F:/abe.data");
        ObjectInputStream ois = new ObjectInputStream(fis);
        User user = null;
        for (int i = 0; i < 200; i++) {
            user = (User) ois.readObject();
            System.out.println(user);
        }
        ois.close();
        fis.close();
    }

    private static void writeObject() throws Exception {
        File file = new File("F:/abe.data");
        FileOutputStream fos = new FileOutputStream(file, true);
        ObjectOutputStream oos = null;
        if (file.length() < 1) {
            oos = new ObjectOutputStream(fos);
        } else {
            oos = new CustomObjectOutputStream(fos);
        }
        for (int i = 0; i < 100; i++) {
            User user = new User();
            user.setId(i);
            user.setUsername("abc" + i);
            user.setPassword("efg" + i);
            oos.writeObject(user);
        }
        oos.close();
        fos.close();
    }

}

 

public class CustomObjectOutputStream extends ObjectOutputStream {
    public CustomObjectOutputStream() throws IOException {
        super();
    }

    public CustomObjectOutputStream(OutputStream out) throws IOException {
        super(out);
    }

    @Override
    protected void writeStreamHeader() throws IOException {
        return;
    }
}

 

你可能感兴趣的:(ObjectOutputStream)