由于原始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();
                }
        }


    }

}

和一个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)

这是因为我认为 –

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.

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

解决方法:

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

如果你想在之后读一个人,写出person对象本身:

stream.writeObject(person);

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

上一篇:java _io_数据流


下一篇:Windows10蓝屏触发及分析