I've got a text file with one customer record per line. Each record is formatted as "ID num, first name, last name, dollar amount". I need to read a line of this text file based on the ID number entered by the user.
I've been following a Java ebook that does this by using the length of a single record and multiplying it by the ID number entered. The problem is, that only works if every record has the exact same length. My records do not truncate or pad out the first and last name, and the dollar amount ranges from two to five characters in length which means that the method that the book uses won't work.
Is there any way to read a specific line in a text file without requiring all the records to be the exact same length? I'd have thought that there would be a way to use the line separator character to do it.
For reference I'll put up the code that doesn't work due to my varying record sizes, in case it helps.
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Path filepath = Paths.get("U:\\Programming\\Java\\Chapter 13\\customersdata.txt");
String s = " , , , 00.00" + System.getProperty("line.separator");
final int RECSIZE = s.length();
byte[] data = s.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(data);
FileChannel fc = null;
try {
fc = (FileChannel)Files.newByteChannel(filepath, READ, WRITE);
System.out.println("Enter an ID number to display the customer details for that ID. Or \"quit\".");
String idString = keyboard.nextLine();
while(!idString.equals("quit")) {
int id = Integer.parseInt(idString);
buffer = ByteBuffer.wrap(data);
fc.position(id * RECSIZE);
fc.read(buffer);
s = new String(data);
System.out.println("ID #" + id + " " + s);
System.out.println("Enter an ID number to display the customer details for that ID. Or \"quit\".");
idString = keyboard.nextLine();
}
fc.close();
}catch(Exception e) {
System.out.println("Error message: " + e);
}
}
EDIT: As the text file being read from could hypothetically contain tens of thousands of records, I can't use Sequential Access, if the ID number I need is near the bottom of the file, it would take an unacceptable amount of time to read them all, as such, the solution must be Random Access.