以前,我已经将一个arraylist数据写入一个名为(ItStateBinary.dat)的二进制文件
现在我试图从二进制文件中读取arraylist,然后将arraylist中的每个元素分配给数组。
到目前为止,我有这个:public CarOwner[] readListFromBinary() throws Exception
{
String fileName = "ItStateBinary.dat";
FileInputStream inStream = new FileInputStream(fileName);
ObjectInputStream objectInputFile = new ObjectInputStream(inStream);
//need to create CarOwner[] object called temp and return
}
readListFromBinary()方法从二进制文件(ltStateBinary.dat)读取ArrayList集合。然后,将每个ArrayList对象项写入新创建的名为temp的CarOwner []。 temp被返回给调用方法。
编辑:
public CarOwner[] readListFromBinary() throws Exception
{
String fileName = "ItStateBinary.dat";
FileInputStream inStream = new FileInputStream(fileName);
ObjectInputStream objectInputFile = new ObjectInputStream(inStream);
ArrayList<CarOwner> read = (ArrayList<CarOwner>)objectInputFile.readObject();
CarOwner[] temp = read.toArray(new CarOwner[read.size()]);
return temp;
}
有人知道这个方法有什么问题吗?它给了我编译器警告
答案 0 :(得分:0)
我不确定你问的是什么,但假设你把ArrayList写成文件就好了 的是:
ArrayList<CarOwner> al = new ArrayList<CarOwner>();
FileOutputStream fos = new FileOutputStream("ItStateBinary.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(al);
这样,你就可以阅读,你已经在做的事情:
FileInputStream fis = new FileInputStream("ItStateBinary.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<CarOwner> read = (ArrayList<CarOwner>)ois.readObject();
然后返回从ArrayList返回数组:
return read.toArray(new CarOwner[read.size()]);