我的代碼 -獲取OptionalDataException因爲原始int值,但如何避免它在JAVA
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();
}
}
}
}
,一人Bean文件。
我在 com.practise變得異常
java.io.OptionalDataException處 java.io.ObjectInputStream.readObject(來源不明) java.io.ObjectInputStream.readObject0(來源不明) .interview.nio.ObjectStreamExample.main(ObjectStreamExample.java:62)
這是越來越凸起,因爲我認爲 -
試圖讀取的對象時 流中的下一個元素是原始數據。在這種情況下,OptionalDataException的 長度字段被設置爲原始數據 立即從該流讀取的字節數,和EOF字段設置爲假 。
但如何避免它,因爲我知道我設定一個原始值,所以避免。?
「*在序列化的上下文中, – 2017-08-20 20:47:39
一個'String'不會被序列化爲包含'char []'的任何其他對象,但是被框架專門處理。 - https://docs.oracle.com/javase/8/docs/platform/serialization/spec/output.html#a933 - 「9.如果對象是java.lang.String,則該字符串被寫爲長度信息後面跟着以修改後的UTF-8編碼的字符串內容。「 - https://docs.oracle.com/javase/8/docs/platform/serialization/spec/serial-arch.html#a4176 - 「使用DataOutput接口中的方法將原始數據類型寫入流中,例如作爲writeInt,writeFloat或writeUTF。「 – 2017-09-11 13:16:18