我的法典
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();
}
}
}
}
一个人是案卷。
我成为例外。
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)
这是因为我认为——
An attempt was made to read an object when the next element in the stream is primitive data. In this case, the OptionalDataException s length field is set to the number of bytes of primitive data immediately readable from the stream, and the eof field is set to false.
但是,如果我知道,如何避免这种做法,那么,那是避免的。