简体   繁体   English

java-从二进制文件中读取arraylist集合,并在新数组中分配每个元素

[英]java - reading an arraylist collection from binary files and assigning each element in new array

Previously, I have wrote a arraylist data into a binary file called (ItStateBinary.dat) 以前,我已经将arraylist数据写入了一个名为(ItStateBinary.dat)的二进制文件中。

and now I am trying to read the arraylist from the binary file, then assign each of the element in arraylist to the array. 现在我试图从二进制文件中读取arraylist,然后将arraylist中的每个元素分配给数组。

so far i have this: 到目前为止,我有这个:

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() method Reads an ArrayList collection from a binary file (ltStateBinary.dat). readListFromBinary()方法从二进制文件(ltStateBinary.dat)中读取ArrayList集合。 Then, each ArrayList object item is then written to a newly created CarOwner[] called temp. 然后,每个ArrayList对象项然后被写入新创建的名为temp的CarOwner []中。 temp is returned to the calling method. temp返回到调用方法。

edit: 编辑:

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

does anybody know whats wrong with this method? 有人知道这种方法有什么问题吗? it gives me compiler warning 它给了我编译器警告

I'm not sure what you asking, but assuming that you write your ArrayList to the file like that: 我不确定您要问的是什么,但是假设您将ArrayList这样写入文件:

ArrayList<CarOwner> al = new ArrayList<CarOwner>();
FileOutputStream fos = new FileOutputStream("ItStateBinary.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(al);

That way, you can just read the way, your are already doing: 这样,您就可以阅读方式,您已经在做:

FileInputStream fis = new FileInputStream("ItStateBinary.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<CarOwner> read = (ArrayList<CarOwner>)ois.readObject();

Then just return you return the array from your ArrayList: 然后返回就可以从ArrayList返回数组:

return read.toArray(new CarOwner[read.size()]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM