为什么这样不能实现循环读取对象数据?请指教!!!!!!!!!!!!!!!!!!!!!!!
//tea.txt 是一个文件,保存的几个类对象
//faculty是保存类的类名字
public static void read()
{try
{ObjectInputStream p=new ObjectInputStream(new FileInputStream( "tea.txt "));
faculty[] t=new faculty[3]; //假设有3个对象
String output=new String();
int i=0;
while(p.available()!=0)
{t[i]=new faculty();
t[i]=(faculty)p.readObject();
output+=t[i].getname()+ " "+t[i].getnum()+ "\n ";
i++;
}
JOptionPane.showMessageDialog(null,output);
p.close();
}
catch(Exception ex)
{
}
}
}
按照我这种方法读不出来,但是我如果单独这样测试的话是有结果的:
t[0]=new faculty();
t[0]=(faculty)p.readObject();
output+=t[0].getname()+ " "+t[0].getnum()+ "\n ";
JOptionPane.showMessageDialog(null,output);
既然这样有结果,那为什么循环没有呢?
并且如果我继续再写一段上面的东西的话,就什么都没有了,好奇怪啊!
------解决方案--------------------ObjectInputStream p=new ObjectInputStream(new FileInputStream( "tea.txt "));
faculty[] t=new faculty[3];
String output= " ";
int i=0;
faculty data = (faculty)p.readObject();
while(data != null) {
t[i]=data;
data = (faculty)p.readObject();
output+=t[i].getname()+ " "+t[i].getnum()+ "\n ";
i++;
if (i> 2) break;
}
p.close();