Here you can find the source of serialize(Serializable obj)
Serializes an Object
to a byte array for storage/serialization.
Parameter | Description |
---|---|
obj | the object to serialize to bytes |
Parameter | Description |
---|---|
RuntimeException | (runtime) if the serialization fails |
public static byte[] serialize(Serializable obj)
//package com.java2s; //License from project: Open Source License import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; public class Main { /**/*from w ww. j av a 2 s . c om*/ * <p>Serializes an <code>Object</code> to a byte array for * storage/serialization.</p> * * @param obj the object to serialize to bytes * @return a byte[] with the converted Serializable * @throws RuntimeException (runtime) if the serialization fails */ public static byte[] serialize(Serializable obj) { ByteArrayOutputStream baos = new ByteArrayOutputStream(512); serialize(obj, baos); return baos.toByteArray(); } /** * <p>Serializes an <code>Object</code> to the specified stream.</p> * * <p>The stream will be closed once the object is written. * This avoids the need for a finally clause, and maybe also exception * handling, in the application code.</p> * * <p>The stream passed in is not buffered internally within this method. * This is the responsibility of your application if desired.</p> * * @param obj the object to serialize to bytes, may be null * @param outputStream the stream to write to, must not be null * @throws IllegalArgumentException if <code>outputStream</code> is <code>null</code> * @throws RuntimeException (runtime) if the serialization fails */ public static void serialize(Serializable obj, OutputStream outputStream) { if (outputStream == null) throw new IllegalArgumentException( "The OutputStream must not be null"); ObjectOutputStream out = null; try { // stream closed in the finally out = new ObjectOutputStream(outputStream); out.writeObject(obj); } catch (IOException ex) { throw new RuntimeException(ex); } finally { try { if (out != null) out.close(); } catch (IOException ex) { // ignore close exception } } } }