以前,我已经将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;
}
有人知道这种方法有什么问题吗?它给了我编译器警告
我不确定您要问的是什么,但是假设您将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()]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句