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.
Solution 1:
You can use it like this..
ArrayList<Object> arrayList = newArrayList<Object>();
Object obj = null;
while ((obj = ois.readObject()) != null) {
arrayList.add(obj);
}
You can return an ArrayList on your method.
return arrayList;
Edit: Full code would be like this..
publicstaticArrayList<Object> load(Context ctx, String filename)
{
InputStream fis = null;
ObjectInputStream ois = null;
ArrayList<Object> arrayList = newArrayList<Object>();
Object loadedObj = null;
try {
fis = ctx.openFileInput(filename);
ois = newObjectInputStream(fis);
while ((loadedObj = ois.readObject()) != null) {
arrayList.add(loadedObj);
}
} catch (Exception e) {
e.printStackTrace();
returnnull;
} finally {
if (null != ois) ois.close();
if (null != fis) fis.close();
}
return arrayList;
}
Hope it helps..
Solution 2:
An extention to @Jan 's code, fixing the problem of keeping ois
open if an exception is thrown, along with some minor issues.
publicstatic ArrayList<Object> load(Context ctx, String filename)throws FileNotFoundException {
InputStreaminstream= ctx.openFileInput(filename);
ArrayList<Object> objects = newArrayList<Object>();
try {
ObjectInputStreamois=newObjectInputStream(instream);
try{
ObjectloadedObj=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();
}
returnnull;
}
Post a Comment for "How Do I Save And Multiple Objects From A Single File?"