无法从Java二进制文件中读取对象信息

问题描述 投票:0回答:1

我正在编写一个程序,该程序将有关汽车的信息保存在对象ArrayList中。我希望能够将ArrayList中的信息保存到二进制文件中,然后在以后加载并查看该信息。

但是我已使保存功能生效,但是我无法使程序读取文件。我得到一个:

“ cars = in.readObject();中的错误。”。

我已将我的代码放在下面,我们将不胜感激。 (PS。我不能将ArrayList交换其他任何东西)

ArrayList<carClass> cars = new ArrayList<carClass>();

public void openFile(){
        cars = null;
      try {
         FileInputStream fileIn = new FileInputStream("yareyare.ora");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         cars = () in.readObject();
         in.close();
         fileIn.close();
        }
        catch (IOException i) {
         i.printStackTrace();
         return;
        }
      }

如果您有兴趣,这就是我要添加到数组中的内容

                System.out.println("What is the make of the car?");
                String newMake = scan.next();
                System.out.println("What is the model of the car?");
                String newModel = scan.next();
                System.out.println("What year was the car produced?");
                String newYear = scan.next();
                System.out.println("How far has this car traveled?");
                String newOdometer = scan.next();
                cars.add(new Car(newMake, newModel, newYear, newOdometer));
java binaryfiles
1个回答
0
投票

您必须将您的对象转换为汽车对象

cars = (Car)in.readObject();
© www.soinside.com 2019 - 2024. All rights reserved.