gpt4 book ai didi

java - 如何将 .txt 文件的最后 5 行读入 java

转载 作者:搜寻专家 更新时间:2023-11-01 03:57:42 26 4
gpt4 key购买 nike

我有一个包含多个条目的文本文件,例如:

hello
there
my
name
is
JoeBloggs

我如何按降序阅读最后五个条目,即从 JoeBloggs - 那里

我目前只有读取最后一行的代码:

public class TestLastLineRead {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream(file.txt);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null, tmp;
while ((tmp = br.readLine()) != null) {
strLine = tmp;
}

String lastLine = strLine;
System.out.println(lastLine);
in.close();
}
}

最佳答案

您可以将这些行添加到 List 中,例如一个 LinkedList。当列表超过五行时,删除第一行/最后一行。

List<String> lines = new LinkedList<String>();
for(String tmp; (tmp = br.readLine()) != null;)
if (lines.add(tmp) && lines.size() > 5)
lines.remove(0);

关于java - 如何将 .txt 文件的最后 5 行读入 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9465269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com