溫馨提示×

java如何獲取文件最后一行

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

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

  1. 創建一個 RandomAccessFile 對象,指定要讀取的文件路徑和打開文件的模式為只讀模式。

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

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

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

  5. 將讀取到的字節轉換為字符,并將字符附加到一個字符串中,以便最后返回。

以下是一個示例代碼:

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

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

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女