How to get current file position during sequential read in Java?

I need to know when I read the last record from a file (or, in another way, I need to know when the next read will return EOF). I would prefer to determine this by getting the current file position, rather than reading further and maintaining a queue with 1 depth.

Below is the problem I'm facing: unfortunately, it looks like myFileChannel.position () tells me the offset of the first position that was not read in the buffer . For example, after the first readline (), position () returns 8192.

Is there a way by which I can get the offset of the first character that readline () was not used?

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); } } 
+4
source share
1 answer

You can try something like getting the size of the entire file in advance. And then, when you read it (maybe in turn), calculate how much you made. Not sure how possible this is for you, just a thought.

0
source

All Articles