Is there a way to read two or more files in a single Java8 thread?

I like the new Java8 StreamAPI and want to use it not only for one file. As usual, I use this code:

Stream<String> lines = Files.lines(Paths.get("/somepathtofile"));

But how to read two files in one stream, if possible?

+4
source share
3 answers

Without any additional helper functions or external libraries, the easiest way is:

Stream<String> lines1 = Files.lines(Paths.get("/somepathtofile"));
Stream<String> lines2 = Files.lines(Paths.get("/somepathtoanotherfile"));

Stream.concat(lines1, lines)
    .filter(...)
    .forEach(...);

If Files.linesit was not announced that he had thrown an excluded exception, you can make

Stream.of("/file1", "/file2")
     .map(Paths::get)
     .flatMap(Files::lines)....

, , . . , Files.lines, , IOException UncheckedIOException. - , . :

@FunctionalInterface
public interface ThrowingFunction<T,R> extends Function<T,R> {

    @Override
    public default R apply(T t) {
        try {
            return throwingApply(t);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static<T,R> Function<T,R> wrap(ThrowingFunction<T,R> f) {
        return f;
    }

    R throwingApply(T t) throws Exception;
}

Stream.of("/somefile", "/someotherfile", "/yetanotherfile")
        .map(Paths::get)
        .flatMap(ThrowingFunction.wrap(Files::lines))
        .....

, - .

+8

cyclops-streams ( )

  SequenceM.of("/somepathtofile1","/somepathtofile2")
             .flatMapFile(File::new)
             .forEach(System.out::println);

Javadoc SequenceM java.util.stream.Stream( org.jooq.lambda.Seq), .

0

Files.list(Paths.get("path"))
            .filter(Files::isRegularFile)
            .flatMap(s -> {
                try {
                    return Files.lines(s);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            })
            .forEach(System.out::println);
0

All Articles