我想在文件中编写对象的arraylist。但是只有一个对象进入file.Atfirst我获取所有存储的对象然后追加新对象之后我将整个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();
}
}
提前帮助我...... thnx
答案 0 :(得分:1)
您正在读取UserDetail
类型的对象,但是要编写ArrayList
类型的对象。应该是:
al = (ArrayList)ois.readObject ();
而不是
al.add ((UserDetail) ois.readObject ());