Java Object Save writeObjectToFile(Object o, String filename)

Here you can find the source of writeObjectToFile(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

Exception

Parameter Description
IOException If can't write file.

Return

File containing the object

Declaration

public static File writeObjectToFile(Object o, String filename) throws IOException 

Method Source Code


//package com.java2s;
import java.io.*;

import java.util.zip.GZIPOutputStream;

public class Main {
    /**// w  ww .ja  va  2 s  .  co m
     * Write object to a file with the specified name.  The file is silently gzipped if the filename ends with .gz.
     *
     * @param o Object to be written to file
     * @param filename Name of the temp file
     * @throws IOException If can't write file.
     * @return File containing the object
     */
    public static File writeObjectToFile(Object o, String filename) throws IOException {
        return writeObjectToFile(o, new File(filename));
    }

    /**
     * Write an object to a specified File.  The file is silently gzipped if the filename ends with .gz.
     *
     * @param o Object to be written to file
     * @param file The temp File
     * @throws IOException If File cannot be written
     * @return File containing the object
     */
    public static File writeObjectToFile(Object o, File file) throws IOException {
        return writeObjectToFile(o, file, false);
    }

    /**
     * Write an object to a specified File. The file is silently gzipped if the filename ends with .gz.
     *
     * @param o Object to be written to file
     * @param file The temp File
     * @param append If true, append to this file instead of overwriting it
     * @throws IOException If File cannot be written
     * @return File containing the object
     */
    public static File writeObjectToFile(Object o, File file, boolean append) throws IOException {
        // file.createNewFile(); // cdm may 2005: does nothing needed
        OutputStream os = new FileOutputStream(file, append);
        if (file.getName().endsWith(".gz")) {
            os = new GZIPOutputStream(os);
        }
        os = new BufferedOutputStream(os);
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(o);
        oos.close();
        return file;
    }
}

Related

  1. writeObject(Object p_object, File p_outFile)
  2. writeObjectToFile(File file, Object o)
  3. writeObjectToFile(File file, Object obj)
  4. writeObjectToFile(final Object o, final File dir)
  5. writeObjectToFile(Object o, File file, boolean append)
  6. writeObjectToFile(Object o, String fileName)
  7. writeObjectToFile(Object obj, File f)
  8. writeObjectToFile(Object obj, String fileName)
  9. writeObjectToFile(Object obj, String path)