Reputation: 98
I'd like create one Stream with data from several files. How I can do it ? There are my java class. Or maybe I should using not BufferReader but other way ? Thanks !!
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.stream.Stream;
public class BuffReader {
public static void main(String[] args) throws FileNotFoundException {
File file1 = new File("src/page_1.txt");
File file2 = new File("src/page_2.txt");
File file3 = new File("src/page_3.txt");
BufferedReader bufferedReader = new BufferedReader(new FileReader(file1));
//*** I'd like get one bufferedReader with file1 + file2 + file3.
Stream<String> stream = bufferedReader.lines(); // get Stream
stream.forEach(e -> System.out.println(e)); // Working with Stream
}
}
Upvotes: 0
Views: 88
Reputation: 54611
You can create one Stream
from the BufferedReader
for each file, combine them into a stream, and then use the Stream#flatMap
method to create a stream that is a concatenation of all these.
import java.util.function.Function;
import java.util.stream.Stream;
public class CombinedStreams
{
public static void main(String[] args)
{
Stream<String> stream0 = Stream.of("line0", "line1");
Stream<String> stream1 = Stream.of("line2", "line3");
Stream<String> stream2 = Stream.of("line4", "line5");
Stream<String> stream = Stream.of(stream0, stream1, stream2)
.flatMap(Function.identity());
stream.forEach(e -> System.out.println(e));
}
}
(Kudos to diesieben07 for the suggested improvement!)
Upvotes: 1
Reputation: 1547
If you don't need a BufferedReader
and the Stream solution is enough, use that.
If you absolutely need a Reader you can use SequenceInputStream
to concatenate the InputStream
s and then create a BufferedReader
from that.
The API is a little clunky since SequenceInputStream
takes an Enumeration
, so you would have to use one of the old collection types like Vector to construct it, but it works.
Upvotes: 1