java如何獲取文件最后一行

小億
369
2023-08-17 11:36:58
欄目: 編程語言

可以使用 java.io.RandomAccessFile 類來實(shí)現(xiàn)獲取文件的最后一行。具體步驟如下:

  1. 創(chuàng)建一個(gè) RandomAccessFile 對(duì)象,指定要讀取的文件路徑和打開文件的模式為只讀模式。

  2. 使用 RandomAccessFile 對(duì)象的 length() 方法獲取文件的總長度。

  3. 通過 RandomAccessFile 對(duì)象的 seek() 方法將文件指針移動(dòng)到文件總長度的前一個(gè)位置。

  4. 從文件指針位置開始逐個(gè)字節(jié)向前讀取,直到讀取到換行符為止??梢允褂?RandomAccessFile 對(duì)象的 readByte() 方法來讀取每個(gè)字節(jié)。

  5. 將讀取到的字節(jié)轉(zhuǎn)換為字符,并將字符附加到一個(gè)字符串中,以便最后返回。

以下是一個(gè)示例代碼:

import java.io.RandomAccessFile;
public class LastLineOfFile {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
try {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
long fileLength = file.length();
file.seek(fileLength - 1);
StringBuilder lastLine = new StringBuilder();
int currentByte = file.readByte();
while (currentByte != -1 && (char) currentByte != '\n') {
lastLine.insert(0, (char) currentByte);
file.seek(file.getFilePointer() - 2);
currentByte = file.readByte();
}
System.out.println("Last line of the file: " + lastLine.toString());
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

注意,這種方法適用于文本文件,對(duì)于二進(jìn)制文件則無法保證正確性。

0