所以,我需要逐行读取一个文本文件,并按字符串返回它们。我可以指定从哪一行读到哪一行。
我的类有 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>
所有行并应用skip
和 limit
到结果流:
Stream<String> stream = Files.lines(Paths.get(fileName))
.skip(fromLine)
.limit(toLine - fromLine);
这会给你一个 Stream
从 fromLine
开始的行数结束于 toLine
.之后,您可以将其转换为数据结构(例如列表)或做任何需要做的事情。
关于java - 我如何从 Java 8 中的文本文件中读取特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50174973/