Search code examples
javasaveserializable

Saving different types of objects


I'm not really sure how else I can state the title but here goes:

I have multiple classes:

DamageType
Proficiencies
Race

These all need to be saved into .ser files. I thought I'd save time by creating a singular method for all 3 so I needed a saving method that parsed all these objects. I had the classes implement Serializable so that I could create the following method:

createFile(Serializable object){
    File file = new File("./src/"+object+".ser");
    file.createNewFile();
    fout = new FileOutputStream(file);
    oos = new ObjectOutputStream(fout);
    oos.writeObject(object);
}

However, when retrieving the object from the file, it returns as a Serializable interface and I'm unable to convert that interface into a class.

public static ArrayList<Serializable> readFolder(File folder, ArrayList<String> exceptions) {
    ArrayList<Serializable> objects = new ArrayList<Serializable>();
    for (File fileEntry : folder.listFiles()) {
        if (!(exceptions.contains(fileEntry.getName()))) {
            if (fileEntry.isDirectory()) {
                readFolder(fileEntry, exceptions);
            } else {
                objects.add(fileEntry);
            }
        }
    }
    return objects;
}

How else can I do it? Do I have to bite the bullet and just create a createFile method for each one?


Solution

  • Here is generic readFolder that reads Objects assuming that there is of same given type of serialized objects under a given folder/file and does not traverse sub-folders.

    public static <T extends Serializable> List<T> readFolder(Class<T> clazz, File file, List<String> exceptions){
        File[] files = file.isDirectory() ? file.listFiles() : new File[]{file};
    
        List<T> objects = new ArrayList<T>();
    
        for ( File f : files ){
            try (ObjectInputStream ois = new ObjectInputStream( new FileInputStream(f) ) ) {
                T object = clazz.cast( ois.readObject() );
                objects.add(object);
            } catch (Exception e) {
                exceptions.add( e.getMessage() );  
            }
        }        
        return objects;
    }
    

    And you can call it like this:

    List<DamageType> dts = readFolder( DamageType.class, new File(""), new ArrayList<>() );