我正在尝试使用对象输出流读取我自己编写的文件,这就是我编写它的方式:
try
{
fout = new FileOutputStream("VehicleOrders.dat");
oos = new ObjectOutputStream(fout);
for(vehicle v:orderList) ///Travesing to array collection of vehicles and typecasting to repective child object then calling individual methods
{
oos.writeObject(v); //Here I have checked 'v' isproperly initialized and has the required properties assigned too
}
}
在此之后,它写入文件,一些数据,我bieleve'v'
的细节然后我尝试读取这样的文件:
fin = new FileInputStream("VehicleOrders.dat"); //this is the same file,
ois = new ObjectInputStream(fin);
vehicle readInstance=null;
while (orderCount>0) //here order count is number of objects in the file kind of meta data
{
readInstance = (vehicle)ois.readObject(); //here 'readInstance' object is set to right object class i.e car but all the properties for some reason are set to null!!!!
if(readInstance != null)
{
orderList.add(readInstance); //read instance is not null ,it has car object but its values are set to zero :(
}
orderCount--;
}
ois.close();
//as u see I can't read it properly,I believe this is because one of these reasons or other:
Maybe the file is not written properly,but I check object v before writing,it is proper
maybe because it has to do some thing with the class it uses and its constructors i.e vehicle and Car which extends vehicle
May be some other reason I am not aware of
答案 0 :(得分:-1)
我想你可能犯了以下错误:
假设您的Car
课程如下:
class Car{
private String color;
.......
......
}
你可能已经写了下面的setter:
public void setColor(String color){
color=color;
}
这应该是:
public void setColor(String color){
this.color=color;
}