Search code examples
javabufferedreaderoffsetrandomaccessfile

Getting byte offset of line in a text file?


I have a text file like

one
two
three
four
five

I need to get the offset of each line in the file. How do I do this in Java?

I have searched through some of the I/O libraries(like BufferedReader and RandomAccessFile) but I'm unable to find a satisfactory answer to this.

Can anyone suggest how to deal with this?


Solution

  • Another approach would be to count the bytes of each line line this

            BufferedReader br = null;   
        try {
    
            String line;
            // in my test each character was one byte
            ArrayList<Integer> byteoffset = new ArrayList<Integer>();
    
            br = new BufferedReader(new FileReader("numbers.txt"));
            Integer l = 0;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                Integer num_bytes = line.getBytes().length;
                System.out.println(num_bytes);
                byteoffset.add( l==0 ? num_bytes : byteoffset.get(l-1)+num_bytes );
                l++;
            }
    
        } catch ( Exception e) {
    
        }
    

    in this example you would also need to add the size of the newline character \n to size of each line