Here you can find the source of load(String name, Class
Parameter | Description |
---|---|
name | The File name. |
resultClass | The object type class. |
Result | The result type. |
public static <Result extends Serializable> Result load(String name, Class<Result> resultClass)
//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; } }