Java ObjectOutputStream Write save(String name, Serializable object)

Here you can find the source of save(String name, Serializable object)

Description

Save the given object into memory under a File called by the given name.dat.

License

Apache License

Parameter

Parameter Description
name The File name.
object The object to be stored.

Return

Will return true if data could be saved, false otherwise.

Declaration

public static boolean save(String name, Serializable object) 

Method Source Code


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

import java.io.*;

public class Main {
    /**/*from   w w  w  . j a  va2s. co  m*/
     * The parent folder;
     */
    private static final String FOLDER_PREF = "saved";
    /**
     * The serialized files' extension.
     */
    private static final String FILE_EXTENSION = ".dat";

    /**
     * Save the given <i>object</i> into memory under a File called by the given <i>name</i>.dat.
     * <p/>
     * Will create folders if necessary.
     *
     * @param name   The File name.
     * @param object The object to be stored.
     * @return Will return {@code true} if data could be saved, {@code false} otherwise.
     */
    public static boolean save(String name, Serializable object) {
        try {
            OutputStream file = new FileOutputStream(getFile(name));
            OutputStream buffer = new BufferedOutputStream(file);
            try (ObjectOutput output = new ObjectOutputStream(buffer)) {
                output.writeObject(object);
                return true;
            }
        } catch (IOException ignored) {
        }
        return false;
    }

    private static File getFile(String name) {
        return new File(getParent(), normalizeName(name));
    }

    private static File getParent() {
        File parent = new File(FOLDER_PREF);
        //noinspection ResultOfMethodCallIgnored
        if (!parent.isDirectory() && !parent.mkdirs())
            throw new RuntimeException("Could not create folder for " + parent.getAbsolutePath());
        return parent;
    }

    private static String normalizeName(String name) {
        if (!name.endsWith(FILE_EXTENSION))
            name = name + FILE_EXTENSION;
        return name;
    }
}

Related

  1. loadTrace(File file)
  2. save(File f, T o)
  3. save(Object o)
  4. save(Object obj, String path)
  5. save(Serializable serialized, String filepath)
  6. saveAllPlaying(Object obj, String path)
  7. saveBinary(File dumpFile, Object object)
  8. saveCompressed(String filename, Object o)
  9. saveData(HashMap data, String filename)