如何在Java中顺序读取期间获取当前文件位置?

时间:2011-06-20 04:30:38

标签: java file position

我需要能够知道我何时从文件中读取了最后一条记录(或者换句话说,我需要知道 next 读取何时返回EOF)。我更愿意通过获取当前文件位置来确定这一点,而不是尝试提前读取并保持1个深度的队列。

下面演示了我遇到的问题:遗憾的是,事实证明,myFileChannel.position()似乎告诉我第一个位置的偏移量尚未被读入缓冲区 的。例如,在第一个readline()之后,position()返回8192.

是否有一种方法可以获取readline()尚未消耗的第一个字符的偏移量?

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);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以尝试预先获取整个文件的大小。然后当你阅读它(可能是逐行)时,计算你做了多少。不确定它是否对你有用,只是一个想法。