繁体   English   中英

Java - 如何使用缓冲区读取器读取文件两次或使用流两次

[英]Java - How to read a file twice using buffer reader or use stream twice

如何使用缓冲区读取器或使用流两次读取文件两次???

  • 我需要在代码中操作大量数据,所以需要考虑性能。

下面的示例代码 1,给出异常“流关闭” -

Url url = 'www.google.com'
InputStream in = url.openStream();
BufferReader br = new BufferReader(in);

Stream<String> ss = br.lines; // read all the lines

List ll = ss.collect();
br.close();
BufferReader br = new BufferReader(in); //exception occurs

下面的示例代码 2 给出了异常“流关闭/正在使用”-

Url url = 'www.google.com'
InputStream in = url.openStream();
BufferReader br = new BufferReader(in);

Supplier<Stream<String>> ss = br.lines; // read all the lines

List ll = ss.collect();
List xx = ss.collect();. // Exception occurs

请忽略语法,这只是一个草稿代码。 请建议。

在使用方面, stream有点类似于iterator ,因为它只能使用一次。

如果您想再次使用同一流的内容,您需要像第一次一样创建一个新流。

从 Java 12 开始,您可以使用Collectors.teeing()方法将同一流的值传递到两个分支中。

List.stream().collect(Collectors.teeing(
                Collector1, // do something with the stream
                Collector2, // do something else with the stream
                BiFunction, use to merge results)

你也可以这样做。

Supplier<Stream<String>> ss1 = br.lines; // read all the lines
Supplier<Stream<String>> ss2 = br.lines; // read all the lines

现在您可以将ss1ss2用作两个单独的流。

下面有一个例子。 您可以根据需要使用它阅读多次。

BufferedReader br = new BufferedReader(new FileReader( "users/desktop/xxx.txt" ));
String strLine;
List<String> ans= new ArrayList<String>();

// Read rows
while ((strLine = br.readLine()) != null) {
    System.out.println(strLine);
    ans.add(strLine);
}

// Read again
for (String result: ans) {
    System.out.println(result);
}

参考

https://www.dreamincode.net/forums/topic/272652-reading-from-same-file-twice/

你不能。 一条小溪就像它现实生活中的水一样。 你可以观察你站在桥下的水,但你不能指示水回到山顶以便你再次观察它。

要么让每个消费者在移动到下一行之前处理每一行,或者如果这是不可能的,那么您将需要创建整个事物的“缓冲区”:即将每一行存储到Collection<String> ,这是第二个(和第三,第四......)消费者可以迭代。 这样做的潜在问题是它的内存开销更大。 在这方面,大多数网站的 HTML 不太可能被证明是一个很大的问题。

通过复制列表可以轻松修复您的最后一个示例。

List ll = ss.collect();
List xx = new ArrayList(ll);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM