Search code examples
javaobjectrandom-accessobjectinputstream

is it possible to access objects randomly in java?


basically I have a file of String Objects. I used Java ObjectOutputStream to store the objects. Is it possible to access the objects(Strings) randomly, say if I want to access the 11th object, I could just somehow jump to that location without having to use readObject() 11th times to loop to that location. And if I wanna to jump back, I could do it also, without having to loop from the start again. Thanks.

As it is suggested, I think I can somehow do use skipBytes() method to realize some sort of random access. Although I can't guarantee that my object is of fixed size, but what if I can keep an array of positions of those objects in the file, I could just use that array as an index and skipBytes() to random access. So the problem remains, anyway that I could know the size of objects when I am actually writing them, so that I could record the position somehow?


Solution

  • The ObjectOutputStream itself cannot do that, because first of all it cannot know the size of the objects in that file; actually, it cannot even know that the objects are of the same type.

    If you know for sure that the objects are fixed-sized and you know that size, you can make use of the skipBytes() method -- but I strongly doubt you really know that.


    EDIT: Thanks for accepting my answer, but (just make things clear): my intention was to show one way this could be done given the requirements that you mentioned, but this is not at all the way it should be done, in my opinion. :)