Getting byte offset of line in a text file?

谁说我不能喝 提交于 2019-12-07 18:33:59

问题


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?


回答1:


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




回答2:


a) Byte offset 0, ie. file start
b) Open the file with something to read binary byte blocks (instead of strings etc.),
read the whole file (in a loop with something like up to 4096 byte each time)
and search the bytes with value '\n' in the block, in each loop iteration.
The position of each '\n' plus the count of previous block * 4096 is another line offset.



来源:https://stackoverflow.com/questions/22135261/getting-byte-offset-of-line-in-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!