如何获取文件最后写入 JAVA 的位置?

How to get position last wrote in a file in JAVA?

我想写一个循环日志文件:

public class CircularLogFile {
    public static final String LOG_FILE_NAME = "circular.log";
    public static final int LOG_FILE_SIZE_MAX = 256;

    public static void write(String line) throws IOException {
        //BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(logFileName, true));
        RandomAccessFile raf = new RandomAccessFile(LOG_FILE_NAME, "rw");
        System.out.println("file size: "+raf.length());
        System.out.println("file pointer: "+raf.getFilePointer());
        if (raf.length() >= LOG_FILE_SIZE_MAX && raf.getFilePointer() >= LOG_FILE_SIZE_MAX) {
            raf.seek(0);
        } else if (raf.length() >= LOG_FILE_SIZE_MAX && raf.getFilePointer() < LOG_FILE_SIZE_MAX) {
        } else if (raf.length() < LOG_FILE_SIZE_MAX) {
            raf.seek(raf.length());
        }

        raf.writeChars(line+"\n");

        raf.close();
    }

    public static void main(String[] args) throws IOException {
        int lineNumber = 0;

        while (true) {
            lineNumber++;
            write("This is Line "+lineNumber);
        }
    }
}

输出:

This is Line 1400
s is Line 2
This is Line 3
This is Line 4
This is Line 5
This is Line 6
This is Line 7
This is Line 8
This is Line 9

不是

This is Line 10
This is Line 11
This is Line 12
This is Line 4
This is Line 5
This is Line 6
This is Line 7
This is Line 8
This is Line 9

我想要上面的结果,但我发现我无法获取文件中最后写入的位置,如何获取?

你想要的是非常棘手的,在我看来它甚至可能不是处理它的最佳方式。您正在使用和滥用 File I/O(昂贵且使用您的 objective,有些困难)。

您是否正在处理如此大的文件,以至于您无法使用数据结构来解析文件并在刷新之前保存输出?它需要最少的计算并最小化 I/O reads/writes,同时使其更易于使用