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
}
You have several general approaches to implementing this:
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.