title: How do I get current file position during sequential read in Java?
body: <p>I need to be able to know when I have read the last record from a file (or, to put it another way, I need to know when the <em>next</em> read will return EOF).  I'd prefer to determine this by obtaining the current file position, rather than trying to read ahead and maintain a 1-deep queue.</p>
  
  <p>The following demonstrates the problem I'm having: unfortunately, it turns out that myFileChannel.position() appears to be telling me the offset to the first position <em>that hasn't been read into the <strong>buffer</em></strong>.  For example, after the first readline(), position() returns 8192.  </p>
  
  <p>Is there a method by which I can obtain the offset of the first character that hasn't been consumed by readline()?</p>
  
  <pre><code>import java.io.BufferedReader;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.InputStreamReader;
  import java.nio.channels.FileChannel;
  
  public final class FilePosition {
  
      public static void main(String[] args) {
          String            myFileName = args[0];
          File              myFile; 
          FileInputStream   myInputStream;
          InputStreamReader myInputStreamReader; 
          FileChannel       myFileChannel;
          BufferedReader    myBufferedReader;
          long              myFileSize;
          long              myFilePosition;
  
          String absDirPath = "/Users/chap/Documents/workspace/FilePosition/bin/";
          myFileName = args[0];
  
          try {
              myFile              = new File(absDirPath + myFileName);
              myInputStream       = new FileInputStream(myFile);
              myInputStreamReader = new InputStreamReader(myInputStream);
              myBufferedReader    = new BufferedReader(myInputStreamReader);
  
              myFileChannel = myInputStream.getChannel();
              myFileSize    = myFileChannel.size();
  
              String inputLine = "";
              while (inputLine != null) {
                  inputLine = myBufferedReader.readLine();
                  // myFilePosition = ?
                  myFilePosition = myFileChannel.position();
                  say(inputLine + "   Size=" + myFileSize + ", Pos=" + myFilePosition);
              }
  
          }
          catch (Exception e) {
              say("Exception caught opening file " + 
                      myFileName + ": " + e.getMessage());
              return;
          }
      }
  
      private static void say(String s) {
          System.out.println(s);
      }
  }
  </code></pre>