[英]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
我想要上面的結果,但是我找不到文件中最后寫入的位置,如何獲得?
您想要的東西非常棘手,在我看來,它甚至可能不是處理它的最佳方法。 您正在使用和濫用文件I / O(昂貴且出於目標,有些困難)。
您是否正在處理如此大的文件,以致無法使用數據結構來解析文件並在刷新之前保留輸出? 它將需要最少的計算並最小化I / O讀/寫,同時使其更易於使用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.