gpt4 book ai didi

java - 附加到 ObjectOuputStream

转载 作者:行者123 更新时间:2023-12-02 11:20:48 25 4
gpt4 key购买 nike

我有一个名为“admin_product.bin”的文件。我想将对象附加到文件中。搜索后发现一个类如下:

public class AppendingObjectOutputStream extends ObjectOutputStream {

public AppendingObjectOutputStream(OutputStream out) throws IOException {
super(out);
}

@Override
protected void writeStreamHeader() throws IOException {
// do not write a header, but reset:
// this line added after another question
// showed a problem with the original
reset();
}

}

上面的代码帮助我们将数据附加到我的文件中。但是,当我尝试使用 ObjectInputStream 读取文件时,它会抛出如下错误:

java.io.StreamCorruptedException: invalid stream header: 79737200

我的代码示例是:

public static void write_into_file() throws IOException {
File file = null;
file = new File("admin_product.bin");

if(!file.exists()) {
ObjectOutputStream os = null;
try {
os = new ObjectOutputStream(new FileOutputStream(file));
os.writeObject(prd);
System.out.println("Done!");
} catch(Exception e) {
System.out.println("Exception = " + e);
} finally {
if(os != null) {
os.close();
}
}

}

else {
AppendingObjectOutputStream as = null;
try {
as = new AppendingObjectOutputStream(new FileOutputStream(file));
as.writeObject(prd);
System.out.println("Done!");
} catch(Exception e) {
System.out.println("Exception = " + e);
} finally {
if(as != null) {
as.close();
}
}
}
}

谁能告诉我哪里出错了?

我有以下问题的答案(但无法找出问题所在)-

1) Appending to a file

2) Appending class error

最佳答案

您没有附加到文件。如果要附加到对象流,则还必须附加到文件,并且不能覆盖已有的内容。

这将覆盖现有文件内容:

new FileOutputStream(file)

附加使用

new FileOutputStream(file, true)

整行是:

as = new AppendingObjectOutputStream(new FileOutputStream(file, true));

关于java - 附加到 ObjectOuputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49930160/

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