Reputation: 83
I'm trying to perform random read/write operations on serializable objects in a file.
I know I can set the position of a FileInputStream
and then wrap the appropriate Input Streams around it like this:
InputStream file = new FileInputStream(fileName);
((FileInputStream)file).getChannel().position(pos);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream (buffer);
But what if I have to change the position of the FileInputStream
again later on to perform another write operation?
How do I change/reset the BufferedInputStream
so it can perform right? Do I even have to?
Also, I am assuming that any answer to this questions also apply to an Output scenario?!
Upvotes: 1
Views: 2001
Reputation: 140525
I agree with EJP: you are going down the wrong rabbit hole here in case you would be asking for a "generic" solution that works for arbitrary classes.
But your comments make it clear that you specially designed your class(es) to result in "equally sized records" when using serialization properly.
What you need to do:
In other words: in order to make this work, you can't read/write more than one object in one shot. You want serialization to be a simple mechanism to turn a single object into a stream of bytes; and vice versa.
But keep in mind: you will spend a lot of energy for a very restricted use case. As soon as your classes would need to be more complex, you are broken - as you now end up with different sized byte representations.
So the real answer here: while your idea can be implemented (and is a nice learning exercise around serialization and file access), you are re-inventing the wheel here! And your version of that wheel is very restricted, hard to enhance; and probably resulting in mediocre performance.
So in case this is intended for a "real" product: better turn to any real database, instead of building your own DBMS.
Upvotes: 2
Reputation: 310980
I'm trying to perform random read/write operations on serializable objects in a file.
Stop right there (and back away). You can't do this via any means. The object stream relies on its own past history, via a system of 'handles', for both classes and objects. You will not in general succeed in this, however you try to realize it in code, for example, by eliminating the buffered stream.
EDIT Serialization does not re-serialize an already serialized object. For example, a StreamClassDesc
, which is provided with every object. Instead it just serializes a 'handle' to it. So even if you just serialize two Strings
, you can't deserialize the second one on its own, because the classdesc handle refers to a prior object in the stream. See the Object Serialization Specification. There is also the stream header to consider.
Upvotes: 1
Reputation: 30137
I think the easier thing you can do is create a new BufferedInputStream
any time you hav to move the position on the FileInputStream
.
Upvotes: 2