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

how can i read specific lines from a textfile in java 8?

所以,我需要逐行读取文本文件,然后 return 按字符串读取它们。我可以指定从哪一行读到哪一行。

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

您可以对所有行使用 Files.lines which returns a Stream<String> 并将 skiplimit 应用于结果流:

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

这将为您提供从 fromLinetoLineStream 行。之后,您可以将其转换为数据结构(例如列表)或做任何需要做的事情。