I have a fixed format file.
I want to access specific lines in this file based on line numbers.
e.g. read line 100
The length of each line is 200 bytes.
So directly moving cursor to 100th line using RandomAccessFile would be like:
File f = new File(myFile);
RandomAccessFile r = new RandomAccessFile(f,"rw");
r.skipBytes(200 * 99); // linesize * (lineNum - 1)
System.out.println(r.readLine());
However, I am getting output as null.
What am I missing here ?
The question is in continuation to answer to my previous question Reaching a specific line in a file using RandomAccessFile
Update:
Below program works exactly as I am expecting:
Line size is 200 characters.
File f = new File(myFile);
RandomAccessFile r = new RandomAccessFile(f,"rw");
r.seek(201 * (lineNumber-1)); // linesize * (lineNum - 1)
System.out.println(r.readLine());
Giving linenumber (any line number from entire file) is printing that line.
@EJP: Please explain!
Firstly, if you are only going to be reading from the file, not writing to it, then I would suggest that you open the RandomAccessFile as “r” rather than “rw”. The reason is that, if the file is open to allow write access, you can actually move the pointer in the file to a location that is larger than the length of the file, because you can potentially write the file as large as you want.
For example, if you have a file of 100 bytes in length, opening it in read-only mode will force you to keep the pointer somewhere in those 100 bytes. However, if you open the same file in read-write mode, you can tell RandomAccessFile to seek(250) and it will obey without any issues, as it thinks that you potentially want to write data out at this point in the file.
So, as some others have stated, its possible that you have moved past the end of the file, which would be quite valid in “rw” mode.
Secondly, if you are going to be reading from the beginning of the file, I would recommend that you use seek() rather than skipBytes(). By using seek(), you are guaranteeing that you are moving to the exact location you want to be, as it is always relative to the start of the file. However, skipBytes() is relative to the current pointer position in the file, so if you accidentally happened to move the pointer somewhere in your code between the RandomAccessFile constructor and the skipBytes() method call, you wouldn’t arrive at the correct spot.
So, if you are going to be working from the beginning of the file, seek() provided a greater level of security that you are going to end up at the correct place in the file, no matter what else you do to the RandomAccessFile.