javaandroidobjectinputstream

How do I save and multiple objects from a single file?


I want my app to store multiple objects locally for later use.

Now, my problem is that I know how to load an object from an ObjectInputStream by taking the entire file(federations.dat). Is there a way for me to load say object WHERE id = N from "federations.dat" ? Or do I have to create separate files for each object?

This is my load method:

public static Object load(Context ctx, String filename) throws FileNotFoundException 
{
    Object loadedObj = null;
    InputStream instream = null;

    instream = ctx.openFileInput(filename);

    try {
        ObjectInputStream ois = new ObjectInputStream(instream);
        loadedObj = ois.readObject();
        return loadedObj;
        
    } catch (StreamCorruptedException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

Any suggestions come to mind ?


Solution

  • An extention to @Jan 's code, fixing the problem of keeping ois open if an exception is thrown, along with some minor issues.

    public static ArrayList<Object> load(Context ctx, String filename) throws FileNotFoundException {
        InputStream instream = ctx.openFileInput(filename);
    
        ArrayList<Object> objects = new ArrayList<Object>();
    
        try {
            ObjectInputStream ois = new ObjectInputStream(instream);
            try{
                Object loadedObj = null;
                while ((loadedObj = ois.readObject()) != null) {
                    objects.add(loadedObj);
                }
    
                return objects;
            }finally{
                ois.close();
            }
    
        } catch (StreamCorruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }