1

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

1
  • Can you show , where do you call this function, and where you initialize your object that you pass as an argument to this function. Commented Feb 18, 2013 at 12:39

1 Answer 1

1

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 ());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.