由于原始int值而获取OptionalDataException,但如何在JAVA中避免它

Abh*_*ary 3 java io serialization datainputstream

我的守则 -

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();
                }
        }


    }

}
Run Code Online (Sandbox Code Playgroud)

和一个Person bean文件.

我越来越异常了

Java.io.OptionalDataException,位于java.io.ObjectInputStream.readObject0(未知源),位于java.io.ObjectInputStream.readObject(未知源),位于com.practise.interview.nio.ObjectStreamExample.main(ObjectStreamExample.java:62)

这是因为我认为 -

当流中的下一个元素是原始数据时,尝试读取对象.在这种情况下,OptionalDataException的长度字段设置为可立即从流中读取的原始数据的字节数,并且eof字段设置为false.

但是如何避免它,因为我知道我设置了原始值,所以要避免.

Chr*_*rau 6

你正在写一篇String并尝试阅读Person.这不是序列化的工作原理.在序列化的上下文中,UTF字符串被认为是原始数据,因为它不包含对象信息(类名,属性等),而只包含字符串数据.

person如果你想要Person事后阅读,请写出对象本身:

stream.writeObject(person);
Run Code Online (Sandbox Code Playgroud)

附录:如果写一个String表现得和其他任何一个一样Object,你会得到一个ClassCastException,因为String无法施展Person.在任何情况下,您所写的内容与您阅读的内容之间的不匹配都会导致您获得的错误.