マイコード -の取得理由はプリミティブなint値のOptionalDataExceptionが、どのように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.ObjectInputStream.readObject(不明なソース)で java.io.ObjectInputStream.readObject0(不明なソース)で例外
java.io.OptionalDataExceptionを取得しています.interview.nio.ObjectStreamExample.main(ObjectStreamExample.java:62)
私は思うので、これが発生なっている -
をストリームの次の要素がプリミティブデータであるときにオブジェクトを読み取ろうとしました。この場合、OptionalDataExceptionの 長さフィールドは、ストリームからすぐに読み取れるプリミティブデータ のバイト数に設定され、eofフィールドは falseに設定されます。
しかし、私が知っているようにそれを避けるために、私はプリミティブな価値を設定しているので、回避する方法はありますか?
「*シリアル化の文脈では、UTF文字列はプリミティブデータ*考えられている」 - ソース? –
'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のように指定します。 –