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

时间:2019-11-03 09:50:39

标签: java binaryfiles

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

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

  

“汽车= 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));

1 个答案:

答案 0 :(得分:0)

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

cars = (Car)in.readObject();