【发布时间】:2021-03-31 22:59:41
【问题描述】:
我正在编写一个小程序,在ArrayList 中插入客户详细信息并将其写入文件。
问题在于ObjectOutputStream 我能够通过转动FileOutputStream("",true) 将数据附加到文件中。但是当我尝试使用ObjectInputStream 读取数据时,它只会读取第一次插入的数据。但数据正在添加到文件中。
这是代码 -
public void insertCustomer() throws IOException
{
Customer1=new customerDetails("1", "Moeen4", "654654", "asdf", "coding", "student", "65464", "3210");
Customer3=new customerDetails("3", "Moeen5", "888888", "asdf", "coding", "student2", "65464", "321022");
Customer4=new customerDetails("4", "Moeen6", "654654", "asdf", "coding", "student", "65464", "7890");
_list=new ArrayList<customerDetails>();
_list.add(Customer1);
_list.add(Customer3);
_list.add(Customer4);
customersList cl=new customersList();
cl.WriteObjectToFile(files._customers, _list);
ArrayList<customerDetails>li=new ArrayList<customerDetails>();
li= (ArrayList) cl.ReadObjectFromFile(files._customers);
for(int i=0;i<li.size();i++)
{ System.out.println(li.size());
System.out.println(li.get(i).Id);
System.out.println(li.get(i).name);
System.out.println(li.get(i).annual_Salary);
System.out.println(li.get(i).Company);
System.out.println(li.get(i).dateOfBirth);
System.out.println(li.get(i).phone_Number);
}
}
public void WriteObjectToFile(String filepath,Object serObj) {
try {
FileOutputStream fileOut = new FileOutputStream(filepath,true);
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(serObj);
objectOut.close();
System.out.println("The Object was succesfully written to a file");
} catch (Exception ex) {
ex.printStackTrace();
}
}
public Object ReadObjectFromFile(String filepath) {
try {
FileInputStream fileIn = new FileInputStream(filepath);
ObjectInputStream objectIn = new ObjectInputStream(fileIn);
Object obj = objectIn.readObject();
objectIn.close();
System.out.println("The Object has been read from the file");
return obj;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
【问题讨论】:
-
您只是从文件中读取一个 ArrayList。当您第二次写入时,另一个 ArrayList 将附加到文件的末尾。您需要继续阅读 ArrayLists 直到到达文件末尾。
-
任何函数可以读取到文件末尾?
-
你不能这样做。您不能在不采取特殊措施的情况下附加到
ObjectOutputStream。最好每次都保持文件打开或完全重写。
标签: java arraylist file-io objectinputstream objectoutputstream