问题描述
我的代码有问题。当我在代码中使用readObject时,我得到IOException。整个程序正常工作,但是当我想使用readObject时,我得到了这个异常,
这是我用来保存对象的代码:
I have problem with my code. I get IOException when I use readObject in my code. the whole program work correctly but when I want to use readObject I get this exception,this is the code I use for saving object:
File f = new File("employees.obj");
ObjectOutputStream objOut = null;
try {
objOut = new ObjectOutputStream(new BufferedOutputStream(
new FileOutputStream(f)));
objOut.writeObject(newEmployee);
objOut.flush();
System.out.println("Object is serialized.");
} catch (FileNotFoundException e) {
System.out.println("File not found!");
} catch (IOException e) {
System.out.println("Failed!");
} finally {
if (objOut != null) {
try {
objOut.close();
} catch (IOException e) {
}
}
}
这是我用来恢复对象的代码:
and it is the code I use for restoring object:
File f = new File("employees.obj");
ObjectInputStream objIn = null;
ArrayList<Employee> c = new ArrayList<Employee>();
try {
objIn = new ObjectInputStream(new BufferedInputStream(
new FileInputStream(f)));
while (objIn.readObject() != null) {
Person employee = (Person) objIn.readObject();
System.out.println("hello");
System.out.println(employee.toString());
}
System.out.println(c.toString());
return c;
} catch (FileNotFoundException e) {
System.out.println("1");
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("3");
} catch (ClassCastException e) {
System.out.println("4");
} finally {
if (objIn != null) {
try {
objIn.close();
} catch (IOException e) {
System.out.println("4");
}
}
}
return c;
以及控制台中的结果:
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2553)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1296)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
at org.bihe.DeSerializer.deSerializeEmployees(DeSerializer.java:20)
at org.bihe.Main.enterAsManager(Main.java:238)
at org.bihe.Main.menu(Main.java:92)
at org.bihe.Main.main(Main.java:50)
推荐答案
while (objIn.readObject() != null) {
将解除一个对象(Person)的分解。然后是下一行:
will deseralize one object (Person). Then the next line:
Person employee = (Person) objIn.readObject();
尝试解除下一个对象的deseralize。如果你在文件的末尾(EOF),那么它会抛出
IOException
。
attempts to deseralize the next object. If you're at the end of the file (EOF), then it throwsIOException
.
要解决此问题,请执行以下操作:
To fix this do something like this:
Person employee;
while ((employee = (Person)objIn.readObject()) != null) {
System.out.println("hello");
System.out.println(employee.toString());
}
while比较 readObject()
with null并将其分配给 employee
。
The while compares readObject()
with null and assigns it to employee
.
这篇关于java中ObjectInputStream中的IOException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!