在Java 中高效檢索文字檔案的最後一行
讀取大型文字檔案的最後一行可能是一項具有挑戰性的任務,尤其是在嘗試避免載入時整個檔案進入記憶體。本文探討了兩種無需遍歷整個文件即可完成此任務的有效方法。
方法1:拖尾檔案
第一種方法,稱為「拖曳」 ,」涉及定位到檔案結尾並逐字元向後迭代,記錄字元直到遇到換行符。 >
public String tail(File file) { try (RandomAccessFile fileHandler = new RandomAccessFile(file, "r")) { long fileLength = fileHandler.length() - 1; StringBuilder sb = new StringBuilder(); for (long filePointer = fileLength; filePointer != -1; filePointer--) { fileHandler.seek(filePointer); int readByte = fileHandler.readByte(); if (readByte == 0xA) { // line break (LF) if (filePointer == fileLength) { continue; } break; } else if (readByte == 0xD) { // carriage return (CR) if (filePointer == fileLength - 1) { continue; } break; } sb.append((char) readByte); } String lastLine = sb.reverse().toString(); return lastLine; } catch (Exception e) { e.printStackTrace(); return null; } }
用法
public String tail2(File file, int lines) { try (RandomAccessFile fileHandler = new RandomAccessFile(file, "r")) { long fileLength = fileHandler.length() - 1; StringBuilder sb = new StringBuilder(); int lineCount = 0; for (long filePointer = fileLength; filePointer != -1; filePointer--) { fileHandler.seek(filePointer); int readByte = fileHandler.readByte(); if (readByte == 0xA) { // line break (LF) if (filePointer < fileLength) { lineCount++; } } else if (readByte == 0xD) { // carriage return (CR) if (filePointer < fileLength - 1) { lineCount++; } } if (lineCount >= lines) { break; } sb.append((char) readByte); } String lastLines = sb.reverse().toString(); return lastLines; } catch (Exception e) { e.printStackTrace(); return null; } }
注意
File file = new File("D:\stuff\huge.log"); System.out.println(tail(file)); System.out.println(tail2(file, 10));
以上是如何在 Java 中有效率地檢索文字檔案的最後一行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!