如何使用缓冲读取器或两次使用流两次读取文件???
下面的示例代码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
请忽略语法,这只是草稿代码。请提出。
下面有一个例子。您可以根据需要使用它多次阅读。
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);
就使用而言,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 results to process)
您也可以这样做。
Supplier<Stream<String>> ss1 = br.lines; // read all the lines
Supplier<Stream<String>> ss2 = br.lines; // read all the lines
现在您可以将ss1
和ss2
用作两个单独的流。