Java Object Save writeObject(File file, Object object)

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

Description

write Object

License

Open Source License

Declaration

public static void writeObject(File file, Object object) 

Method Source Code

//package com.java2s;
/*/*from   ww w . j a  va2 s . c  om*/
 * Copyright (c) 2015 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 */

import java.io.Closeable;
import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class Main {
    public static void writeObject(File file, Object object) {
        mkdirs(file.getParentFile());

        OutputStream outputStream = null;

        try {
            outputStream = new FileOutputStream(file);

            @SuppressWarnings("resource")
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);
            oos.writeObject(object);
            oos.flush();
        } catch (RuntimeException ex) {
            throw ex;
        } catch (Error ex) {
            throw ex;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            close(outputStream);
        }
    }

    public static void mkdirs(File folder) throws RuntimeException {
        if (folder != null) {
            if (!folder.isDirectory()) {
                if (!folder.mkdirs()) {
                    throw new RuntimeException("Unable to create directory " + folder.getAbsolutePath()); //$NON-NLS-1$
                }
            }
        }
    }

    public static void close(Closeable closeable) throws RuntimeException {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}

Related

  1. writeObject(File f, Object obj)
  2. writeObject(File f, Serializable obj)
  3. writeObject(File file, Object obj)
  4. writeObject(File file, Object object)
  5. writeObject(File file, Object object)
  6. writeObject(File file, Object object)
  7. writeObject(File file, Object object)
  8. writeObject(File outFile, Object data)
  9. writeObject(Object data, String filename)