gpt4 book ai didi

java - 如何通过字节缓冲区写入对象?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:08:28 24 4
gpt4 key购买 nike

我正在尝试:

  • 将一个对象(或一系列不同类型/类别的对象)写入文件
  • 复读
  • 检查实例并再次将它们转换为相同类型/类的对象

我可以找到这两个类,这就是我使用它们的方式。但是 data[] 数组对我来说意义不大。为什么一定要在 deserialize 方法中放入一个空的数据数组?

public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
return out.toByteArray();
}
public static Object deserialize(byte[] data)
throws IOException, ClassNotFoundException {
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return is.readObject();
}

public static void main(String[] args) {

try {
Thing p = new Thing(2,4);

byte[]data = new byte[10240];
serialize(p);
Object des = deserialize(data);

} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(Pruebiña.class.getName())
.log(Level.SEVERE, null, ex);
}

}

我该如何解决这个问题?现在我遇到以下错误,当程序到达 deserialize 行时:

java.io.StreamCorruptedException: invalid stream header: 00000000
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:806)

我能做些什么来解决这个问题,并能够写回和读回对象?是的,Thing 类是Serializable

最佳答案

如果你想写一个文件你根本不需要字节数组使用FileInputStream 和 FileOutputStream 例如。

public static void serialize(Object obj, File f) throws IOException {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f))) {
out.writeObject(obj);
}
}

public static Object deserialize(File f)
throws IOException, ClassNotFoundException {
try (ObjectInputStream is = new ObjectInputStream(new FileInputStream(f))) {
return is.readObject();
}
}

static class Thing implements Serializable {
int a,b,c;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {

File f = new File("object.dat");
Thing orig = new Thing();
serialize(orig, f);
Thing back = (Thing) deserialize(f);
}

关于java - 如何通过字节缓冲区写入对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32389054/

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