Serialize an object to a file - Java File Path IO

Java examples for File Path IO:Serialization

Description

Serialize an object to a file

Demo Code


import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.logging.*;

public class Main{
    /**//from  w  w w  . j a  va  2 s.  c o m
     * Serialize an object to a file
     * @param object The object to serialize.
     * @param filename The filename of the serialized object
     */
    public static void serializeObject(Object object, String filename) {
        System.out.println("Serializing " + filename);
        try {
            FileOutputStream fileOut = new FileOutputStream(filename);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(object);
            out.close();
            fileOut.close();
        } catch (IOException ex) {
            Logger.getLogger(HelperFunctions.class.getName()).log(
                    Level.SEVERE, null, ex);
        }

        System.out.println("Done serializing " + filename);
    }
}

Related Tutorials