Store objects in file : ObjectInputStream « File Input Output « Java






Store objects in file

  

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 + "]";
  }
}

   
    
  








Related examples in the same category

1.Create ObjectInputStream out of FileInputStreamCreate ObjectInputStream out of FileInputStream
2.new ObjectInputStream(new BufferedInputStream(new FileInputStream(StringFileName)));
3.Reading objects from file using ObjectInputStream
4.Read different data types from ObjectInputStream
5.Object serialization with Serializable interface, ObjectOutputStream and ObjectInputStream.
6.ObjectInputStream, ObjectOutputStream and java.io.Serializable
7.Use ObjectOutputStream and ObjectInputStream to write and read Hashtable
8.ObjectStream Test with hierarchy