【发布时间】:2012-05-09 09:09:09
【问题描述】:
我的代码-
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectStreamExample {
/**
* @param args
*/
public static void main(String[] args) {
Person person = new Person();
person.setFirstName("Abhishek");
person.setLastName("Choudhary");
person.setAge(25);
person.setHouseNum(256);
ObjectOutputStream stream = null;
try {
stream = new ObjectOutputStream(new FileOutputStream(new File("Serialize.txt")));
stream.writeUTF(person.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(stream != null)
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream(new File("Serialize.txt")));
Person person2 = (Person) input.readObject();
System.out.println(person2.getFirstName());
System.out.println(person2.getLastName());
System.out.println(person2.getAge());
System.out.println(person2.getHouseNum());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
if(input != null)
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
还有一个 Person bean 文件。
我遇到了异常
java.io.OptionalDataException 在 java.io.ObjectInputStream.readObject0(未知来源)在 java.io.ObjectInputStream.readObject(Unknown Source) 在 com.practise.interview.nio.ObjectStreamExample.main(ObjectStreamExample.java:62)
之所以提出这个问题,是因为我认为 -
尝试读取对象时, 流是原始数据。在这种情况下,OptionalDataException 的 长度字段设置为原始数据的字节数 立即从流中读取,并且 eof 字段设置为 假的。
但是如何避免它,因为我知道我设置了一个原始值,所以要避免。?
【问题讨论】:
标签: java serialization io datainputstream