共計 929 個字符,預計需要花費 3 分鐘才能閱讀完成。
可以使用 java.io.RandomAccessFile
類來實現獲取文件的最后一行。具體步驟如下:
- 創建一個
RandomAccessFile
對象,指定要讀取的文件路徑和打開文件的模式為只讀模式。 - 使用
RandomAccessFile
對象的length()
方法獲取文件的總長度。 - 通過
RandomAccessFile
對象的seek()
方法將文件指針移動到文件總長度的前一個位置。 - 從文件指針位置開始逐個字節向前讀取,直到讀取到換行符為止。可以使用
RandomAccessFile
對象的readByte()
方法來讀取每個字節。 - 將讀取到的字節轉換為字符,并將字符附加到一個字符串中,以便最后返回。
以下是一個示例代碼:
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();
}
}
}
注意,這種方法適用于文本文件,對于二進制文件則無法保證正確性。
丸趣 TV 網 – 提供最優質的資源集合!
正文完
發表至: Java
2023-12-21