I'm trying to seek through a RandomAccessFile, and as part of an algorithm I have to read a line, and then seek backwards from the end of the line
E.g
String line = raf.readLine();
raf.seek (raf.getFilePointer() - line.length() + m.start() + m.group().length());
//m is a Matcher for regular expressions
I've been getting loads of off-by-one errors and couldn't figure out why. I just discovered it's because some files I'm reading from have UNIX-style linefeeds, \r\n, and some have just windows-style \n.
Is there an easy to have the RandomAccessFile treat all linefeeds as windows-style linefeeds?
You could always back the stream up two bytes and re-read them to see if it is \r \n or (!\r)\n:
String line = raf.readLine();
raf.seek(raf.getFilePointer()-2);
int offset = raf.read() == '\r' ? 2 : 1;
raf.read(); //discard the second character since you know it is either \n or EOF by definition of readLine
raf.seek (raf.getFilePointer() - (line.length()+offset) + m.start() + m.group().length());
I'm not sure exactly where you are trying to place the file pointer, so adjust the 2/1 constants appropriately. You may also need to add an extra check for blank lines (\n\n) if they occur in your file, as if it shows up you might get stuck in an infinite loop without code to step past it.