Search code examples
javaserializationrandom-access

Using Random Access File to Update part of a file in Java


I am trying to use Random access file to update a binary tree. But I only want to update the nodes that have just been modified instead of rewriting the whole tree everytime I add a node. I have two questions so far:

I'm having a issue writing a object to a file using RandomAccessFile. Since it is a node object, RAF doesn't have any read/write methods. I did implement Serializable for my tree class but still not sure how to write the tree out to file.

Node<String> mynode = new Node<String>();
RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw");
raf.write(mynode, 0, 100);

which I am getting an error because mynode is not a byte[].

My second issue is I am not sure how to seek the file to overwrite. What I did is add a extra field in node for a id and i keep a hashmap for id:position to locate where to modify. Not sure if this is the right way


Solution

  • I don't think that your approach is going to work the way you think it will. RandomAccessFile is used for reading and writing bytes at an arbitrary position. You could certainly take your object and serialize it to a byte array that you then write to an RAF (or just write the serialized bytes using a fileoutputstream) - but that's not going to help you when you want to update a record because the serialized form of the record will probably be of different length each time you change it.

    As mentioned in one of the comments, what you are looking for is a database - a higher level abstraction than the simple linear chain of bytes that RandomAccessFile will give you access to.

    If you are looking for a file based storage system that can read and write records (i.e. a light-weight, embedded database), check out jdbm2 - it also has built in b-tree structures (which are a lot better for file based stores than a binary tree).