Search code examples
javafilerandom-access

Reaching a specific line in a file using RandomAccessFile


Is it possible to position cursor to the start of a specific line in a file through RandomAccessFile?

For e.g. I want to change String starting at char 10 till 20 in line 111 in a file. The file has fixed length records.

Is it possible to directly position the cursor to start of line 111 using RandomAccessFile ?

Update:

I used the following code. However, its returning null.

Line length is 200 characters (which is 200 bytes if I am not wrong)

File f = new File(myFile); 
RandomAccessFile r = new RandomAccessFile(f,"rw"); 
r.skipBytes(200 * 99);   // linesize * (lineNum - 1) 
System.out.println(r.readLine());

Where am I going wrong ?


Solution

  • I'm not sure but seems RandomAccessFile do not support such functionality. As RAF operates with bytes we can skip specific amount of bytes, and if your file has fixed line width this can be achieved by

    file.skipBytes(110 * lineSizeInBytes);
    

    Otherwise, you need something like this:

    for (int i = 0; i < 110; i++) file.readLine();
    String line = file.readLine();