gpt4 book ai didi

Java 8 流 : Read file word by word

转载 作者:搜寻专家 更新时间:2023-10-31 20:00:49 24 4
gpt4 key购买 nike

我经常使用 Java 8 流来处理文件,但到目前为止总是逐行处理。

我想要的是一个函数,它获取一个 BufferedReader br 并且应该读取特定数量的单词(由 "\\s+" 分隔)并且应该离开BufferedReader 在准确的位置,达到字数的地方。

现在我有一个版本,它按行读取文件:

    final int[] wordCount = {20};
br
.lines()
.map(l -> l.split("\\s+"))
.flatMap(Arrays::stream)
.filter(s -> {
//Process s
if(--wordCount[0] == 0) return true;
return false;
}).findFirst();

这显然将 Inputstream 留在了下一行的位置第20个字。
有没有办法获得从输入流中读取少于一行的流?

编辑
我正在解析一个文件,其中第一个单词包含后续单词的数量。我读了这个词,然后相应地读入了具体的字数。该文件包含多个这样的部分,其中每个部分都在所描述的函数中进行解析。

阅读了所有有用的评论后,我很清楚,使用 Scanner 是解决此问题的正确选择,并且 Java 9 将有一个 Scanner 类它提供流功能(Scanner.tokens()Scanner.findAll())。
以我描述的方式使用 Streams 无法保证读者将在流的终端操作( API docs )之后处于特定位置,因此使流成为解析结构的错误选择,您只在其中解析一个部分,必须跟踪位置。

最佳答案

关于您的原始问题:我假设您的文件如下所示:

5 a section of five words 3 three words
section 2 short section 7 this section contains a lot
of words

你想得到这样的输出:

[a, section, of, five, words]
[three, words, section]
[short, section]
[this, section, contains, a, lot, of, words]

一般来说,Stream API 不太适合这类问题。在这里编写普通的旧循环看起来是一个更好的解决方案。如果您仍想查看基于 Stream API 的解决方案,我建议您使用我的 StreamEx包含 headTail() 的库方法允许您轻松编写自定义流转换逻辑。以下是如何使用 headTail 解决您的问题:

/* Transform Stream of words like 2, a, b, 3, c, d, e to
Stream of lists like [a, b], [c, d, e] */
public static StreamEx<List<String>> records(StreamEx<String> input) {
return input.headTail((count, tail) ->
makeRecord(tail, Integer.parseInt(count), new ArrayList<>()));
}

private static StreamEx<List<String>> makeRecord(StreamEx<String> input, int count,
List<String> buf) {
return input.headTail((head, tail) -> {
buf.add(head);
return buf.size() == count
? records(tail).prepend(buf)
: makeRecord(tail, count, buf);
});
}

使用示例:

String s = "5 a section of five words 3 three words\n"
+ "section 2 short section 7 this section contains a lot\n"
+ "of words";
Reader reader = new StringReader(s);
Stream<List<String>> stream = records(StreamEx.ofLines(reader)
.flatMap(Pattern.compile("\\s+")::splitAsStream));
stream.forEach(System.out::println);

结果看起来与上面期望的输出完全一样。将 reader 替换为您的 BufferedReaderFileReader 以从输入文件中读取。记录流是惰性的:流一次最多保留一条记录,如果你短路,输入的其余部分将不会被读取(好吧,当然当前文件行会被读取到最后).该解决方案虽然看起来是递归的,但不会占用堆栈或堆,因此它也适用于大文件。


解释:

headTail() 方法接受一个双参数 lambda,当请求流元素时,它在外部流终端操作执行期间最多执行一次。 lambda 接收第一个流元素(head)和包含所有其他原始元素的流(tail)。 lambda 应该返回一个新的流,它将被用来代替原来的流。在 records 中,我们有:

return input.headTail((count, tail) -> 
makeRecord(tail, Integer.parseInt(count), new ArrayList<>()));

输入的第一个元素是 count:将其转换为数字,创建空的 ArrayList 并为尾部调用 makeRecord。下面是 makeRecord 辅助方法实现:

return input.headTail((head, tail) -> {

第一个流元素是head,将它添加到当前缓冲区:

    buf.add(head);

达到目标缓冲区大小?

    return buf.size() == count 

如果是,再次调用 tailrecords(处理下一条记录,如果有的话)并在结果流前添加单个元素:当前缓冲区。

            ? records(tail).prepend(buf)

否则,为尾部调用自己(向缓冲区添加更多元素)。

            : makeRecord(tail, count, buf);
});

关于Java 8 流 : Read file word by word,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35275884/

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