Store objects in file : ObjectInputStream « File « Java Tutorial






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

public class Main {
  public static void main(String[] args) throws Exception {
    FileOutputStream fos = new FileOutputStream("books.dat");
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    Book book = new Book("1", "Java", "A");

    oos.writeObject(book);
    oos.flush();
    oos.close();
    FileInputStream fis = new FileInputStream("books.dat");
    ObjectInputStream ois = new ObjectInputStream(fis);
    book = (Book) ois.readObject();
    System.out.println(book.toString());

    ois.close();
  }
}

class Book implements Serializable {
  private String isbn;

  private String title;

  private String author;

  public Book(String isbn, String title, String author) {
    this.isbn = isbn;
    this.title = title;
    this.author = author;
  }

  public String toString() {
    return "[Book: " + isbn + ", " + title + ", " + author + "]";
  }
}








11.22.ObjectInputStream
11.22.1.Create ObjectInputStream from FileInputStream
11.22.2.Reading objects from file using ObjectInputStream
11.22.3.Object serialization with Serializable interface, ObjectOutputStream and ObjectInputStream.
11.22.4.Store objects in file