I need to get the current filepointer-position (in bytes) when I read from my binary file.
I wrote the file using ObjectOutputStream
, and now I need to read it and remember the byte-position of each object.
However: ObjectInputStream
doesn't provide a method to read the pointer position, and RandomAccessFile
cannot read Objects :(
If you think there's a way, or even a workaround, this extra information might help:
I have stored IDs in my file. Each ID lists at least one node (can be many nodes). All as Long-Values.
For Example:
ID Node Node ...
123151824812 12419512 1248129412 124912 5992039 1924823590
5238952323942 283492384 234892348 234908234 2348902348 5902303 239235523
...
Each ID is an individual object which stores the id-value itself as a long value, the nodes as an ArrayList<Long>
.
There's a second file which stores Nodes and lists the parenting IDs of each Node. Like this:
Node ID ID ...
12419512 123151824812
234892348 5238952323942 27834918128911
...
The idea behind is: Whenever I know an ID and want to know information about the node, then I look which node is at the specific position in the node-file. Whenever I know the node and want to know more about its parenting ID, then I look at the specific position in the ID file.
However currently I did just write the ID and Node-values itself into the files using them as "index".
I don't want to look line-for-line if that's the ID I'm looking for, as these files can become very large (GB-size). It would be easier if I remember the byte-position of the other file instead of a line-index or so, because then I can simply jump to it using skip() or similar methods.
Conclusion: How to get the file pointer position (in bytes) from the beginning of the next object while reading from an ObjectInputStream
?
I have not tried this, but typically you would create your ObjectInputStream like this
FileInputStream fis = new FileInputStream("filename.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
From the FileInputStream
, you can call getChannel()
which returns a FileChannel
. On the FileChannel
there is a method position()
which returns the current file position.
I would think as long as you have not buffering input stream in between, position()
should return the right value.