1

我想在文件中写入对象的数组列表。但只有一个对象进入文件。首先我获取所有存储的对象,然后附加新对象,然后将整个 arrayList 写入文件。

这是我的代码....

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();
    }
}

帮帮我……提前谢谢

4

1 回答 1

1

您正在读取类型的对象,UserDetail但正在写入类型的对象ArrayList。应该是:

al = (ArrayList)ois.readObject ();

代替

al.add ((UserDetail) ois.readObject ());
于 2013-02-18T12:39:15.180 回答