问题
I'm trying to create a system where a user can choose a set of ID's(Federation IDs) to retrieve data from an external API. After the data is retrieved from the web service I wish to store it 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 ?
回答1:
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;
}
回答2:
You can use it like this..
ArrayList<Object> arrayList = new ArrayList<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..
public static ArrayList<Object> load(Context ctx, String filename)
{
InputStream fis = null;
ObjectInputStream ois = null;
ArrayList<Object> arrayList = new ArrayList<Object>();
Object loadedObj = null;
try {
fis = ctx.openFileInput(filename);
ois = new ObjectInputStream(fis);
while ((loadedObj = ois.readObject()) != null) {
arrayList.add(loadedObj);
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (null != ois) ois.close();
if (null != fis) fis.close();
}
return arrayList;
}
Hope it helps..
来源:https://stackoverflow.com/questions/11257667/how-do-i-save-and-multiple-objects-from-a-single-file