我需要逐行处理文件并想知道行首的偏移量。因为BufferedInputStream中没有readLine,所以我自己编写了readLine。它工作正常,除了偏移量。当文件长度变长时,偏移量返回不正确的值。我的代码有什么问题?
class MyBufferedInputStream extends BufferedInputStream {
long offset = 0;
public MyBufferedInputStream(InputStream in) {
super(in);
}
public String readLine() throws IOException {
int b, i = 0;
byte[] buf = new byte[256];
while (true) {
b = read();
offset++;
if (b == -1)
return null;
else if (b == '\n')
return (new String(buf));
else // assume line in not longer than 256
buf[i++] = (byte) b;
}
}
public long getOffset() {
return offset;
}
public void resetOffset() {
offset = 0;
}
}