Save and Read Object in Java

Description

The following code shows how to save and Read Object.

Example


/*from   w  w w  .  ja v  a2  s  .c  o  m*/
import java.awt.Polygon;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Main {
  public static void main(String[] args) {
    int[] x = new int[] { 1, 2, 3 };
    int[] y = new int[] { 4, 5, 6 };
    Polygon polygon = new Polygon(x, y, x.length);
    try {
      ObjectOutputStream objectOut = new ObjectOutputStream(new BufferedOutputStream(
          new FileOutputStream("Polygons.bin")));
      objectOut.writeObject(polygon);
      objectOut.close();
    } catch (IOException e) {
      e.printStackTrace(System.err);
    }
    try {
      ObjectInputStream objectIn = new ObjectInputStream(new BufferedInputStream(
          new FileInputStream("Polygons.bin")));
      Polygon theLine = (Polygon) objectIn.readObject();
      System.out.println(theLine);
      objectIn.close();
    } catch (Exception e) {
      e.printStackTrace(System.err);
    }
  }
}

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