Java ObjectOutputStream and updating a file

2020-05-02 10:55发布

问题:

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?

回答1:

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.