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 tha开发者_Go百科t 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?
The only way you can do this is to store the objects separately in their own streams, either within the same file or in different files.
It is likely that the simplest thing to do is to store your Objects in a List, and then read that list in one read, and access the List randomly.
This is not possible with ObjectInputStream
, if you need random access you will need to read all the objects into a Collection/array which supports random access first.
Using ObjectOutputStream
to store String objects is complete overkill. You've already thought of using an index of starting positions. Then why not just store the strings directly into the file using a FileOutputStream
- either wrap it in an OutputStringWriter
using a fixed length encoding (where the number of bytes == length of string, possibly *2), or use toBytes(encoding)
on each string individually and note the length of the resulting byte arrays.
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. :)
精彩评论