Serializing an Object - Java File Path IO

Java examples for File Path IO:Serialization

Description

Serializing an Object

Demo Code

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class Main {
  public void m() {
    Object object = new javax.swing.JButton("push me");

    try {/*from  ww w  .  ja  v  a 2s  .  c  o m*/
      // Serialize to a file
      ObjectOutput out = new ObjectOutputStream(new FileOutputStream(
          "filename.ser"));
      out.writeObject(object);
      out.close();

      // Serialize to a byte array
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      out = new ObjectOutputStream(bos);
      out.writeObject(object);
      out.close();

      // Get the bytes of the serialized object
      byte[] buf = bos.toByteArray();
    } catch (IOException e) {
    }
  }
}

Related Tutorials