0

My app reads text file line by line and record offset of each line until the end of file. But position() always returns 0. What is wrong with my code?

String buffer;
long offset;
RandomAccessFile raf = new RandomAccessFile("data.txt", "r");
FileChannel channel = raf.getChannel();
BufferedReader br = new BufferedReader(new InputStreamReader(Channels.newInputStream(channel)));

while (true) {
    offset = channel.position(); // offset is always 0. why?
    if ((buffer = br.readLine()) == null) // buffer has correct value.
        return;
    ………………………………
}
Hoopje
  • 12,677
  • 8
  • 34
  • 50
user3152056
  • 169
  • 2
  • 10
  • If you want an `InputStream`, why not directly use a `FileInputStream`? That is at least potentially more efficient than getting a `FileChannel` and wrapping it in an `InputStream`. – Brett Okken Jan 25 '15 at 14:20

1 Answers1

0

I cannot reproduce your error, that is, offset is not always 0 when I run your code. Still, it doesn't do what you expect it to do. You create a BufferedReader on top of your FileChannel. The BufferedReader will fill its buffer (and thus increase the offset in the channel) and then read from the buffer until its empty. So after calling br.readLine() once, the offset is not the length of the string you've read, it is the length of the buffer.

You can better use a BufferedReader and FileInputStream directly and count the characters by some other means.

Hoopje
  • 12,677
  • 8
  • 34
  • 50
  • You are right. It update once after readLine the first time. But it never updates. I use getBytes to get offset. It works. Thank you. – user3152056 Jan 30 '15 at 22:43