[英]Which is the best way to read the last line of a text file in Java?
當我想用Java獲取純文本文件的最后一行時,我很困惑。 我怎樣才能做到這一點? 哪個是不使用掃描儀的最佳方式?
謝謝
最簡單的方法是迭代文件中的行,並在到達結尾時停止。 例如:
// I assume this is disposed properly etc
private static String getLastLine(BufferedReader reader) throws IOException {
String line = null;
String nextLine;
while ((nextLine = reader.readLine()) != null) {
line = nextLine;
}
return line;
}
這將為空讀者返回null。
除非我知道我將要閱讀一個非常大的文件,這就是我要做的。 試圖通過直接跳到最后一行來做到這一點很難 。 真的很難,特別是如果你需要一個可變寬度編碼,如UTF-8。
你可以使用RandomAccessFile 1.轉到文件的末尾(新文件(“your_file”)。length())2。讀取char並在循環中使用隨機訪問文件的seek方法。 3.當你看到“\\ n”(或系統中的任何內容)停止時。 4.從您停止的位置重新讀取文件,直到文件結束。 如果你以某種方式記住你到目前為止所閱讀的內容,這是可選的
只需google獲取RandomAccessFile示例。
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.