Java Object Save writeObjectToFileNoExceptions(Object o, String filename)

Here you can find the source of writeObjectToFileNoExceptions(Object o, String filename)

Description

Write object to a file with the specified name.

License

Open Source License

Parameter

Parameter Description
o object to be written to file
filename name of the temp file

Return

File containing the object, or null if an exception was caught

Declaration

public static File writeObjectToFileNoExceptions(Object o, String filename) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.*;

import java.util.zip.GZIPOutputStream;

public class Main {
    /**/*www . j  av a2 s.com*/
     * Write object to a file with the specified name.
     *
     * @param o
     *          object to be written to file
     * @param filename
     *          name of the temp file
     *
     * @return File containing the object, or null if an exception was caught
     */
    public static File writeObjectToFileNoExceptions(Object o, String filename) {
        File file = null;
        ObjectOutputStream oos = null;
        try {
            file = new File(filename);
            // file.createNewFile(); // cdm may 2005: does nothing needed
            oos = new ObjectOutputStream(
                    new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(file))));
            oos.writeObject(o);
            oos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeIgnoringExceptions(oos);
        }
        return file;
    }

    /**
     * Provides an implementation of closing a file for use in a finally block so
     * you can correctly close a file without even more exception handling stuff.
     * From a suggestion in a talk by Josh Bloch.
     *
     * @param c
     *          The IO resource to close (e.g., a Stream/Reader)
     */
    public static void closeIgnoringExceptions(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    }
}

Related

  1. writeObjectToFile(String fileName, Object obj)
  2. writeObjectToFile(String filename, Serializable s)
  3. writeObjectToFile(String filename, T object)
  4. writeObjectToFile(String outputFileName, Object toWrite, boolean append)
  5. writeObjectToFile(T object, File fileHandle)