Java Object Deserialize from File deserialize(String filename)

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

Description

Convenience method used to deserialize objects from a file

License

Apache License

Parameter

Parameter Description
T a parameter
filename a parameter

Exception

Parameter Description
FileNotFoundException an exception
IOException an exception
ClassNotFoundException an exception

Declaration

@SuppressWarnings("unchecked")
public static <T> T deserialize(String filename)
        throws FileNotFoundException, IOException, ClassNotFoundException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.BufferedInputStream;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

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

import java.util.zip.GZIPInputStream;

public class Main {
    /**/* w  w w.j a  va  2s. co m*/
     * Convenience method used to deserialize objects from a file
     * 
     * @param <T>
     * @param filename
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     * @throws ClassNotFoundException
     */
    @SuppressWarnings("unchecked")
    public static <T> T deserialize(String filename)
            throws FileNotFoundException, IOException, ClassNotFoundException {
        return (T) deserialize(new BufferedInputStream(new FileInputStream(filename)));
    }

    /**
     * Convenience method used to deserialize objects from an arbitrary input stream.
     * Note: this method does not wrap the stream with a BufferedInputStream. For 
     * deserializing objects from files, consider using deserialize(String filenam).
     * 
     * @param <T>    the type of the object to return
     * @param is   the input stream to deserialize from
     * @return      the deserialized object
     * @throws IOException   if there is a problem during deserialization
     * @throws ClassNotFoundException   if the class to be deserialized is missing
     */
    @SuppressWarnings("unchecked")
    private static <T> T deserialize(InputStream is) throws IOException, ClassNotFoundException {

        ObjectInputStream ois;
        is.mark(100);
        try {
            ois = new ObjectInputStream(new GZIPInputStream(is));
        } catch (IOException o) {
            is.reset();
            ois = new ObjectInputStream(is);
        }
        T object = (T) ois.readObject();
        ois.close();
        return object;
    }
}

Related

  1. deserialize(File file)
  2. deserialize(File file)
  3. deserialize(File file, Class clazz)
  4. deserialize(final File file)
  5. deserialize(final String path)
  6. deserialize(String fileName)
  7. deserialize(String filename)
  8. Deserialize(String filePath)
  9. deserialize(String filePath)