gpt4 book ai didi

java - 使用给定起始行号和结束行号的 Java 读取文件

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:07:09 26 4
gpt4 key购买 nike

我是 Java 编程的新手,我无法在任何地方找到我的问题的答案。

如何读取文件的几行并将其存储在 String(或字符串列表)中。

例如,从一个 1000 行的文件中,我只需要读取从第 200 行到第 400 行的 200 行。

我遇到了 FileInputStream 使用它我们可以定义起始位置但我们不能定义结束位置。

最佳答案

您不能直接这样做。您只能通过阅读并忽略您不关心的第一行来做到这一点。

您可以使用 Java 的 LineNumberReader 来做到这一点.用它来读取文件,一次读取一行。继续阅读并忽略行,直到到达第 200 行,开始处理数据,一旦到达 400 就停止。

注意:在你问之前,不,LineNumberReader#setLineNumber 改变文件位置,它只是人为设置报告的行号:

By default, line numbering begins at 0. This number increments at every line terminator as the data is read, and can be changed with a call to setLineNumber(int). Note however, that setLineNumber(int) does not actually change the current position in the stream; it only changes the value that will be returned by getLineNumber().

另一种选择是只使用 BufferedReader ,调用 readLine() 199 次以跳到第 200 行,然后读取接下来的 200(或其他)行。但是,LineNumberReader 只是方便地为您跟踪行号。

从 Java 8 开始,第三种选择是使用 streams API并做类似的事情:

Files.lines(Paths.get("input.txt"))
.skip(200) // skip to line 200
.limit(200) // discard all but the 200 lines following this
.forEach(...)

通过您的处理ConsumerforEach()

无论哪种方式,相同的概念:您必须读取并丢弃文件的前 N ​​行,您无法绕过这一点。


LineNumberReader 示例:

LineNumberReader reader = new LineNumberReader(new FileReader("input.txt"));

for (String line = reader.readLine(); line != null; line = reader.readLine()) {
if (reader.getLineNumber() > 400) {
break; // we're done
} else if (reader.getLineNumber() >= 200) {
// do something with 'line'
}
}

BufferedReader 的例子,不像上面的那么简单:

BufferedReader reader = new BufferedReader(new FileReader("input.txt"));

// skip to the 200th line
for (int n = 0; n < 199 && reader.readLine() != null; ++ n)
;

// process the next 201 (there's 201 lines between 200 and 400, inclusive)
String line;
for (int n = 0; n < 201 && (line = reader.readLine()) != null; ++ n) {
// do something with 'line'
}

上面已经给出了使用 Files 的示例。

你想如何在你的 forwhile 或任何循环中组织 EOF 等的条件和测试更多是个人品味的问题,这些只是任意的示例。

关于java - 使用给定起始行号和结束行号的 Java 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39183869/

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