Java Object Save writeObject(File file, Object obj)

Here you can find the source of writeObject(File file, Object obj)

Description

Write one object to the specified file.

License

Open Source License

Parameter

Parameter Description
file the specified file
obj the object to write

Exception

Parameter Description
IOException if IO error occurs

Declaration

public static void writeObject(File file, Object obj) throws IOException 

Method Source Code

//package com.java2s;

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;

import java.io.ObjectOutputStream;

public class Main {
    /**/*from  w  w  w. jav  a 2s . co  m*/
     * Write one object to the specified file.
     * 
     * @param file
     *            the specified file
     * @param obj
     *            the object to write
     * @throws IOException
     *             if IO error occurs
     */
    public static void writeObject(File file, Object obj) throws IOException {
        createFileIfNotExist(file);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(obj);
        oos.close();
    }

    /**
     * Create the specified file if it not exists.
     * 
     * @param file
     *            the specified file
     * @return true if the file exists or created successfully, false otherwise.
     * @throws IOException
     *             If an I/O error occurred
     */
    public static boolean createFileIfNotExist(File file) throws IOException {
        if (file.exists())
            return true;
        else {
            File parent = file.getParentFile();
            if (parent != null && parent.mkdirs())
                return file.createNewFile();
            else
                return false;
        }
    }
}

Related

  1. writeObject(File f, Object obj)
  2. writeObject(File f, Serializable obj)
  3. writeObject(File file, Object object)
  4. writeObject(File file, Object object)
  5. writeObject(File file, Object object)
  6. writeObject(File file, Object object)