Java Byte Array to Object deserialize(byte[] bytes)

Here you can find the source of deserialize(byte[] bytes)

Description

Deserializes a byte array into an object.

License

Apache License

Parameter

Parameter Description
bytes the byte array to deserialize

Exception

Parameter Description
IOException if the deserialization fails
ClassNotFoundException if no class found to deserialize into

Return

the deserialized object

Declaration

public static Serializable deserialize(byte[] bytes) throws IOException, ClassNotFoundException 

Method Source Code


//package com.java2s;
/*//from w w w  . j  a  v  a2 s.co m
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

import java.io.ByteArrayInputStream;

import java.io.IOException;
import java.io.ObjectInputStream;

import java.io.Serializable;

public class Main {
    /**
     * Deserializes a byte array into an object. When the bytes are null, returns null.
     *
     * @param bytes the byte array to deserialize
     * @return the deserialized object
     * @throws IOException if the deserialization fails
     * @throws ClassNotFoundException if no class found to deserialize into
     */
    public static Serializable deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        if (bytes == null) {
            return null;
        }
        try (ByteArrayInputStream b = new ByteArrayInputStream(bytes)) {
            try (ObjectInputStream o = new ObjectInputStream(b)) {
                return (Serializable) o.readObject();
            }
        }
    }

    /**
     * Wrapper around {@link #deserialize(Object)} which throws a runtime exception with the given
     * message on failure.
     *
     * @param bytes the byte array the deserialize
     * @param errorMessage the message to show if deserialization fails
     * @return the deserialized object
     */
    public static Serializable deserialize(byte[] bytes, String errorMessage) {
        try {
            return deserialize(bytes);
        } catch (Exception e) {
            throw new RuntimeException(errorMessage, e);
        }
    }
}

Related

  1. deserialize(byte[] bytes)
  2. deserialize(byte[] bytes)
  3. deserialize(byte[] bytes)
  4. deserialize(byte[] bytes)
  5. deserialize(byte[] bytes)