获取文本文件中行的字节偏移量? [英] Getting byte offset of line in a text file?
本文介绍了获取文本文件中行的字节偏移量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文本文件,如
one
two
three
four
five
我需要获取文件中每一行的偏移量。我如何用Java做到这一点?
I need to get the offset of each line in the file. How do I do this in Java?
我搜索了一些I / O库(如BufferedReader和RandomAccessFile),但我找不到满意的答案对此。
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?
推荐答案
另一种方法是计算每一行的字节数
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) {
}
在这个例子中,您还需要将换行符\ n的大小添加到每行的大小
in this example you would also need to add the size of the newline character \n to size of each line
这篇关于获取文本文件中行的字节偏移量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文