Java I/O How to - Get an array of bytes corresponding to the given object








Question

We would like to know how to get an array of bytes corresponding to the given object.

Answer

 //w  ww. j a v a  2s.co m

/**
 * EasyBeans
 * Copyright (C) 2006 Bull S.A.S.
 * Contact: easybeans@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: Serialization.java 1970 2007-10-16 11:49:25Z benoitf $
 * --------------------------------------------------------------------------
 */


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * Allow to get the bytes of an object or to recreate an object from bytes.<br>
 * It also used a custom reader when recreating object as it uses the context
 * classloader in order to have an object with the right classloader.
 * @author Florent Benoit
 */
public final class Serialization {
    /**
     * Gets an array of bytes corresponding to the given object.
     * @param object the object to serialize
     * @return an array of bytes.
     * @throws IOException if the object can't be turned into an array of bytes.
     */
    public static byte[] storeObject(final Serializable object) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos  =  null;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            oos.flush();
            return baos.toByteArray();
        } finally {
            if (oos != null)  {
                oos.close();
            }
            if (baos != null) {
                baos.close();
            }
        }
    }
}