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

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

Description

Deserializes the given byte array into to a newly allocated object.

License

Apache License

Parameter

Parameter Description
bytes byte array to deserialize or null for null result

Return

new allocated object or null for null input

Declaration

public static <S extends Serializable> S deserialize(byte[] bytes) throws IOException 

Method Source Code


//package com.java2s;
/*//  w w w. ja v  a 2  s  . co m
 * Copyright (c) 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

import java.io.ByteArrayInputStream;

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

import java.io.Serializable;

public class Main {
    /**
     * Deserializes the given byte array into to a newly allocated object.
     *
     * @param bytes byte array to deserialize or {@code null} for {@code null} result
     * @return new allocated object or {@code null} for {@code null} input
     * @since 1.16
     */
    public static <S extends Serializable> S deserialize(byte[] bytes) throws IOException {
        if (bytes == null) {
            return null;
        }
        return deserialize(new ByteArrayInputStream(bytes));
    }

    /**
     * Deserializes the given input stream into to a newly allocated object, and close the input
     * stream.
     *
     * @param inputStream input stream to deserialize
     * @since 1.16
     */
    @SuppressWarnings("unchecked")
    public static <S extends Serializable> S deserialize(InputStream inputStream) throws IOException {
        try {
            return (S) new ObjectInputStream(inputStream).readObject();
        } catch (ClassNotFoundException exception) {
            IOException ioe = new IOException("Failed to deserialize object");
            ioe.initCause(exception);
            throw ioe;
        } finally {
            inputStream.close();
        }
    }
}

Related

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