Java ObjectOutputStream Write load(String name, Class resultClass)

Here you can find the source of load(String name, Class resultClass)

Description

Load data of type resultClass from the File called by the given name.dat.

License

Apache License

Parameter

Parameter Description
name The File name.
resultClass The object type class.
Result The result type.

Return

The object restored, or null if it couldn't be restored.

Declaration

public static <Result extends Serializable> Result load(String name, Class<Result> resultClass) 

Method Source Code


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

import java.io.*;

public class Main {
    /**/*from  w w  w . j  ava  2 s. c om*/
     * The parent folder;
     */
    private static final String FOLDER_PREF = "saved";
    /**
     * The serialized files' extension.
     */
    private static final String FILE_EXTENSION = ".dat";

    /**
     * Load data of type <i>resultClass</i> from the File called by the given <i>name</i>.dat.
     *
     * @param name        The File name.
     * @param resultClass The object type class.
     * @param <Result>    The result type.
     * @return The object restored, or {@code null} if it couldn't be restored.
     */
    public static <Result extends Serializable> Result load(String name, Class<Result> resultClass) {
        try {
            InputStream file = new FileInputStream(getFile(name));
            InputStream buffer = new BufferedInputStream(file);
            try (ObjectInput input = new ObjectInputStream(buffer)) {
                return resultClass.cast(input.readObject());
            }
        } catch (ClassNotFoundException | IOException ignored) {
        }
        return null;
    }

    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. load(File file)
  2. load(File file, Class type)
  3. load(File file, final ClassLoader... loaders)
  4. load(String fileName)
  5. load(String filename)
  6. load(String path)
  7. loadAllPlaying(String path)
  8. loadData(Class expectedClass, String filename)
  9. loadData(HashMap data, String filename)