gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:41:24 27 4
gpt4 key购买 nike

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

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

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

最佳答案

您想要的东西非常棘手,在我看来,这甚至可能不是处理它的最佳方式。您正在使用和滥用文件 I/O(昂贵且对于您的目标来说有点困难)。

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

关于java - 如何获取JAVA文件中最后写入的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38419669/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com