如何将对象读入文件我使用 ObjectInputStream 和 ObjectOutputStream 类来读取和写入我的自定义类 Student 的对象,用于此演示。
编写和读取代码使用::
try
{
if(af.filepath==null || af.filepath=="")//file path
{
JOptionPane.showMessageDialog(null, "Please Set File Path", "File Path Error", JOptionPane.ERROR_MESSAGE);
}
else
{
FileOutputStream fs=new FileOutputStream(af.filepath,true);
ObjectOutputStream fo=new ObjectOutputStream(fs);
fo.writeObject(af.s);//write the Super Class Object
fo.close();
}
}
catch (Exception ex)
{
System.out.println(ex);
}
---------------------------------------------------------------------------------
try
{
if(af.filepath==null || af.filepath=="")//file path have whole path of the file
{
JOptionPane.showMessageDialog(null, "Please Set File Path", "File Path Error", JOptionPane.ERROR_MESSAGE);
}
else
{
Student sp;
FileInputStream fs=new FileInputStream(af.filepath);
ObjectInputStream fo=new ObjectInputStream(fs);
while ((sp=(Student)fo.readObject())!=null)
{
sp.set();//for print object
}
fo.close();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
使用这个我读取文件中的第一个对象,但之后引发错误