Store objects in file in Java

Description

The following code shows how to store objects in file.

Example


//from   w  ww .ja  v a 2 s  .c  o m
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 + "]";
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip