【问题标题】:how can i read specific lines from a textfile in java 8?如何从 java 8 中的文本文件中读取特定行?
【发布时间】:2023-11-12 11:07:01
【问题描述】:

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

我的班级有 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 工作? 提前致谢

【问题讨论】:

    标签: java text-files filereader


    【解决方案1】:

    您可以使用Files.lines,它会在所有行中返回Stream&lt;String&gt;,并将skiplimit 应用于结果流:

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

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

    【讨论】:

      最近更新 更多