Java ObjectInputStream Read All readAll(String filename)

Here you can find the source of readAll(String filename)

Description

deserializes the given file and returns the objects from it.

License

Open Source License

Parameter

Parameter Description
filename the file to deserialize from

Exception

Parameter Description
Exception if deserialization fails

Return

the deserialized objects

Declaration

public static Object[] readAll(String filename) throws Exception 

Method Source Code

//package com.java2s;
/*//from   w ww. j  av a  2  s.  co  m
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   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, see <http://www.gnu.org/licenses/>.
 */

import java.io.*;
import java.util.Vector;

public class Main {
    /**
     * deserializes the given file and returns the objects from it.
     * 
     * @param filename the file to deserialize from
     * @return the deserialized objects
     * @throws Exception if deserialization fails
     */
    public static Object[] readAll(String filename) throws Exception {
        return readAll(new FileInputStream(filename));
    }

    /**
     * deserializes from the given stream and returns the object from it.
     * 
     * @param stream the stream to deserialize from
     * @return the deserialized object
     * @throws Exception if deserialization fails
     */
    public static Object[] readAll(InputStream stream) throws Exception {
        ObjectInputStream ois;
        Vector<Object> result;

        if (!(stream instanceof BufferedInputStream)) {
            stream = new BufferedInputStream(stream);
        }

        ois = new ObjectInputStream(stream);
        result = new Vector<Object>();
        try {
            while (true) {
                result.add(ois.readObject());
            }
        } catch (IOException e) {
            // ignored
        }
        ois.close();

        return result.toArray(new Object[result.size()]);
    }
}