如何用对象流循环读取文件?

来源:百度知道 编辑:UC知道 时间:2024/06/21 12:30:11
我用的
try{
FileInputStream file1=new FileInputStream("file1.txt");//这个文件里面已经存储多个customer类的对象
ObjectInputStream in=new ObjectInputStream(file1);
while((a=(customer)in.readObject())!=null)
{
System.out.println(a.ID+""+a.age);
}
}
catch(IOException e)
{
System.out.println(e);
}
catch(ClassNotFoundException event)
{
System.out.println(event);
}
但是这个算法只能得到文件中第一个customer的对象?求教
一楼的算法,我知道可行,但是加进去之后,我的代码还是有问题。

使用fileInputStream.available==0 作为文件结束的标志。

import java.io.*;

public class Test {

public static void main(String[] args) throws Exception{
FileOutputStream output=new FileOutputStream("file.dat");

ObjectOutputStream out=new ObjectOutputStream(output);

out.writeObject(new Customer(1));
out.writeObject(new Customer(2));
out.writeObject(new Customer(3));
out.writeObject(new Customer(4));
out.writeObject(new Customer(5));
out.writeObject(new Customer(6));

out.close();
output.close();

//ObjectInputStream in=new ObjectInputStream(new FileInputStream("file.dat"));
FileInputStream fileInputStream=new FileInputStream("file.dat");
ObjectInputStream in=new ObjectInputStream(fileInputStream);

while(fileInputStream.available()!=0){
System.out.println(in.readObject());
}

in.close();
fileInputSt