gpt4 book ai didi

java - 我如何从 Java 8 中的文本文件中读取特定行?

转载 作者:行者123 更新时间:2023-11-29 10:09:14 25 4
gpt4 key购买 nike

所以,我需要逐行读取一个文本文件,并按字符串返回它们。我可以指定从哪一行读到哪一行。

我的类有 3 个方法:

public class FilePartReader {

String filePath;
Integer fromLine;
Integer toLine;

public FilePartReader() { }

public void setup(String filepath, Integer fromLine, Integer toLine) {
if (fromLine < 0 || toLine <= fromLine) {
throw new IllegalArgumentException(
"fromline cant be smaller than 0 and toline cant be smaller than fromline");
}
this.filePath = filepath;
this.fromLine = fromLine;
this.toLine = toLine;
}

public String read() throws IOException {
String data;
data = new String(Files.readAllBytes(Paths.get(filePath)));
return data;
}

public String readLines() {
return "todo";
}
}

read() 方法应该打开文件路径,并将内容作为字符串返回。readLines() 应该用 read() 和 从 fromLine 和 toLine 之间的内容返回每一行(它们都包括在内),并将这些行作为字符串返回。现在,我不确定 read() 是否正确实现,因为如果我理解正确,它将整个内容作为一个大字符串返回,也许对此有更好的解决方案?另外,我怎样才能使 fromLine/toLine 工作?提前致谢

最佳答案

您可以使用 Files.lines返回 Stream<String>所有行并应用skiplimit到结果流:

Stream<String> stream = Files.lines(Paths.get(fileName))
.skip(fromLine)
.limit(toLine - fromLine);

这会给你一个 StreamfromLine 开始的行数结束于 toLine .之后,您可以将其转换为数据结构(例如列表)或做任何需要做的事情。

关于java - 我如何从 Java 8 中的文本文件中读取特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50174973/

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