这是我的第一个文件
public class ObjectStream
{
public static void main(String args[]) throws FileNotFoundException, IOException
{
java.io.File f=new java.io.File("D:Employee.outt") ;
Employee e=new Employee("John");
Employee e1=new Employee("Mary");
Employee e2=new Employee("Christian");
OutputStream os=new java.io.FileOutputStream(f);
java.io.ObjectOutputStream oos= new ObjectOutputStream(os);
oos.writeObject(e);
oos.writeObject(e1);
oos.writeObject(e2);
}
}
这是我的第二个文件
public class Employee implements java.io.Serializable
{
private static int count=100;
private int eid;
private String ename;
public Employee()
{
count++;
this.eid=count;
}
public Employee(String ename)
{
this();
this.ename=ename;
}
public static int getCount() {
return count;
}
public static void setCount(int count) {
Employee.count = count;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
}
这是我的第三个文件
public class MainClass
{
public static void main(String args[]) throws FileNotFoundException, IOException, ClassNotFoundException
{
File f=new File("D:Employee.outt");
byte data[]=new byte[(int)f.length()];
InputStream is=new java.io.FileInputStream(f);
java.io.ObjectInputStream ois=new java.io.ObjectInputStream(is);
Object o=ois.readObject();
while(o!=null)
{
Employee e=(Employee)o;
System.out.println(e.getEid());
System.out.println(e.getEname());
o=ois.readObject();
}
ois.close();
is.close();
}
}
我试图通过第三个文件读取 Employee.outt 中存储的对象,但它正在读取所有对象,但最后抛出
Exception in thread "main" java.io.EOFException.
不知道如何解决。
最佳答案
while(o!=null)
这不是读取 ObjectInputStream 的有效方法。
如果您写入了 null,则 readObject()
方法仅返回 null。在流末尾,它会抛出一个 EOFException,因此读取流的正确方法是循环调用 readObject() 直到捕获该异常,然后中断并关闭流。
at the end of file it is giving EOF exception
这正是 EOFException
的含义。
关于java - 无法解析 java.io.EOFException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22705024/