Reputation: 1842
I want to write arraylist of objects in a file. But only one object in going in file.Atfirst I am fetching all the stored objects and then appending new object after that I write whole arrayList to the file.
Here is my code....
public void write(UserDetail u1) throws FileNotFoundException {
ArrayList<UserDetail> al = new ArrayList<UserDetail>();
FileInputStream fin = new FileInputStream(FILEPATH);
try {
if (fin.available() != 0) {
ObjectInputStream ois = new ObjectInputStream(fin);
while (fin.available() != 0 && ois.available() != 0) {
try {
al.add((UserDetail) ois.readObject());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ois != null) {
ois.close();
}
}
}
}
al.add(u1);
FileOutputStream fos = new FileOutputStream(FILEPATH);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(al);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
throw e;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
help me......thnx in advance
Upvotes: 1
Views: 1914
Reputation: 13890
You are reading object of type UserDetail
but writing object of type ArrayList
. Should probably be:
al = (ArrayList)ois.readObject ();
instead of
al.add ((UserDetail) ois.readObject ());
Upvotes: 1