gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:31:31 25 4
gpt4 key购买 nike

我的代码-

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 对象本身,如果你想在之后读取一个 Person:

stream.writeObject(person);

附录:如果编写一个 String 的行为与任何其他 Object 一样,您将得到一个 ClassCastException相反,因为 String 无法转换为 Person。无论如何,您所写内容和所阅读内容之间的不匹配导致了您遇到的错误。

关于java - 由于原始 int 值而获取 OptionalDataException,但如何在 JAVA 中避免它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10370616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com