Search code examples
javarandomaccessfile

How should I write a POJO representation to a RandomAccessFile?


I have a POJO which has a number of String fields. I want to write instances of this object (sorted to natural ordering) to a RandomAccessFile and then eventually search this file for the objects I need.

The problem is I'm not too sure how to go about this - for example, in a plain text file I would delimit a new object instance with, say, a new line. With RandomAccessFile should I be using the the size of the object in bytes to indicate a new object in the file - and if I know I want the second object, I would look at 2 object's worth of bytes into the file?

I've followed tutorials that write sorted integers to file - and if I want to find the second occurrence I would look 8 bytes into the file. Should I be applying the same logic with my POJO - or could I just delimit using a new line?

Edit* these are my object's fields:

import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;

/**
 * A RegradeRule is an individual rule found in the Regrade .dat file (one
 * line).
 * 
 * @author E Rowlands
 */
public class RegradeRule implements Serializable,  Comparable<RegradeRule> { 

    private String privateData;
    private String privateData;
    private String privateData;
    private String privateData;
    private String privateData;
    private String privateData;
    private String privateData;
    private String privateData;
    private String privateData;
    private String privateData;
    private String privateData;
    private String privateData;

    // getters & setters
}

Solution

  • You have several general approaches to implementing this:

    • Use fixed-length strings - decide that your strings have a certain maximum length, and pad all strings that you write to that length with some unused character (say, zero). You will need to deal with encoding of your strings if you are to allow Unicode code points past 127.
    • Write an index at the top of the file or in a separate file - Add a separate block of data at the top of the file to help you navigate to the correct item. This approach makes it difficult to grow the file beyond a certain limit, because the content needs to get copied or read into memory for expansion.
    • Do not use RandomAccessFile if you always get the whole file at once - this is the simplest approach to implement, and you get a human-viewable/editable text file. The drawback to this approach is that you can no longer navigate to a specific item without reading the rest of the items.