Java Object Serialize serialize(Serializable object)

Here you can find the source of serialize(Serializable object)

Description

Serialize an object to a byte array

License

Open Source License

Declaration

public static byte[] serialize(Serializable object) throws IOException 

Method Source Code

//package com.java2s;
/**/*from   ww w  .  j a  v a 2  s  .c  o m*/
 * e-Science Central Copyright (C) 2008-2013 School of Computing Science,
 * Newcastle University
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 2 as published by the
 * Free Software Foundation at: http://www.gnu.org/licenses/gpl-2.0.html
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, 5th Floor, Boston, MA 02110-1301, USA.
 */

import java.io.*;

public class Main {
    /**
     * Serialize an object to a byte array
     */
    public static byte[] serialize(Serializable object) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutputStream stream = new ObjectOutputStream(buffer);
        stream.writeObject(object);
        stream.flush();
        stream.close();
        return buffer.toByteArray();
    }

    /**
     * Serialize to an output stream
     */
    public static void serialize(Serializable object, OutputStream outStream) throws IOException {
        ObjectOutputStream stream = new ObjectOutputStream(outStream);
        stream.writeObject(object);
        stream.flush();
        stream.close();
        outStream.flush();
    }

    /**
     * Write an object to a file
     */
    public static void serialize(Serializable object, File outFile) throws IOException {
        FileOutputStream fileStream = new FileOutputStream(outFile);
        ObjectOutputStream objStream = new ObjectOutputStream(fileStream);
        objStream.writeObject(object);
        objStream.flush();
        fileStream.flush();
        fileStream.getFD().sync();
        objStream.close();
        fileStream.close();
    }
}

Related

  1. serialize(Serializable obj)
  2. serialize(Serializable obj, String fileName)
  3. serialize(Serializable obj, String path)
  4. serialize(Serializable object)
  5. serialize(Serializable object)
  6. serialize(Serializable object)
  7. serialize(Serializable object, File dest)
  8. serialize(Serializable object, String fileName)
  9. serialize(Serializable s, File dir, String fileName)