Java ObjectOutputStream 和更新文件

发布于 2024-12-19 17:23:14 字数 696 浏览 5 评论 0原文

我无法解决一个实现问题,我有一个类,它的行为类似于列表,但不是将文件保存在某个集合中,而是将它们保存在磁盘上。

当我想向列表中添加一些元素时,就会出现问题。在文件的开头,我有一个 int 告诉我列表中有多少个对象,但我无法找出更新该值的优雅方法。我有这样的东西:

   public boolean add(T element)
{
    try 
    {
        out.writeObject(element);
        out.flush();
        //and here we need to update the int in my file
    } catch (IOException e) 
    {
        e.printStackTrace();
    } 
    return true;
}

我尝试使用这样的东西:

ObjectOutputStream upd=new ObjectOutputStream(new FileOutputStream(data.getAbsolutePath(),true));

但据我观察,它会将一些数据写入文件的开头,一些序列化标头或其他东西,我如何更新文件中的单个条目或如何更改

ObjectOutputStream

“指针” “写在文件的开头?

I am having trouble figuring out one implementation problem, I have one class, it behaves like list but instead of holding a file in some collection it saves them on a disk.

The problem occurs when I want to add some element to my list. At the start of my file I have one int that tells me how many objects there are in my list, but I can't figure out elegant way to update this value. I have something like this:

   public boolean add(T element)
{
    try 
    {
        out.writeObject(element);
        out.flush();
        //and here we need to update the int in my file
    } catch (IOException e) 
    {
        e.printStackTrace();
    } 
    return true;
}

I tried to use something like this:

ObjectOutputStream upd=new ObjectOutputStream(new FileOutputStream(data.getAbsolutePath(),true));

but as I observed it writes some data to the start of the file, some serialization header or sth, how can I update single entry in my file or how to change

ObjectOutputStream

"pointer" to write at the beginning of the file?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吃兔兔 2024-12-26 17:23:14

通常,对于基于流的类(尤其是像 OOS 这样的高阶流),您应该在每次更新文件时重写整个文件。

如果您确实坚持只更新文件的一部分,那么您应该将该文件视为由 N 个流组成,其中每个“流”代表您正在写入的一个对象。所以我会使用 RandomAccessFile 作为基本文件,然后当我想写入一个对象时,我会将 ObjectOutputStream 包装在 ByteArrayOutputStream 之上,将对象写入其中,然后获取这些字节,并将这些字节重写到 RandomAcessFile 中,其中你想要的。

这可能不会特别有效,因为您将为正在编写的对象编写 N 个 OOS 标头和 N 个类描述。

Typically with stream based classes (especially higher order streams like OOS), you should rewrite the whole file, anytime you update it.

If you really INSIST on only updating part of a file, then you should think of the file as made up of N streams, where each 'stream' represents one object that you are writing. So i would use a RandomAccessFile for the base file, and then when i want to write an object i would wrap an ObjectOutputStream on top of a ByteArrayOutputStream, write your object into that, then take those bytes, and rewrite those bytes into the RandomAcessFile where you want.

This probably won't be particularly efficient, as you will write N OOS headers, and N class descriptions for the object you are writing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文