我的代码-
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 at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.readObject(Unknown Source) at com.practise.interview.nio.ObjectStreamExample.main(ObjectStreamExample.java:62)
这是因为我认为 -
当流中的下一个元素是原始数据时,尝试读取对象。在这种情况下,OptionalDataException 的长度字段设置为可立即从流中读取的原始数据的字节数,并且 eof 字段设置为 false。
但是如何避免它,因为我知道我设置了一个原始值,所以要避免。?