Java Reference
In-Depth Information
}
} else if (file.isFile()) {
return Stream.of(new Result<>(file));
} else {
return Stream.empty();
}
}
);
} catch (IOException ioe) {
return Stream.of(new Result<>(ioe));
}
}
Now we just have to glue the two together. Again, we will take a boolean to determine whether or not
we will recurse into subdirectories. The stream of files that we will be consuming is a Stream of Result
instances, so we have to decide what to do with errors and what to do with results. Errors will just get passed
along, wrapped as a Stream and then flattened back into the stream. The FunFile instances in the stream,
however, will have their getLines() method called, which will return a stream and then that stream will be
flattened into the stream. The result will be a flat stream of lines (and errors) generated by reading the lines
out of all of the files. That is Listing 4-10. All the work of this chapter built up to that one, simple method.
Listing 4-10. The FunFile. getLinesInDirectory(boolean) Method
/**
* Provides all the lines of all the files in a directory. If this file
* is not a directory, return a stream with a single element, which is a
* single {@link Result} instance with an {@link IOException}. Otherwise,
* return the concatenated stream of trying to read all the lines of all
* the files in the directory using {@link #getLines()}, recursing into
* subdirectories if the {@code recurse} argument is {@code true}.
*
* @param recurse Whether to recurse into subdirectories
* @return The lines of all the files; never {@code null}
*/
public Stream<Result<String>> getLinesInDirectory(boolean recurse) {
if (!isDirectory()) {
return Stream.of(new Result<>(new IOException(
"File is not a directory: " + toString()
)));
}
Function<Exception, Stream<Result<String>>> onError =
ex -> Stream.of(new Result<>(ex));
Function<FunFile, Stream<Result<String>>> onResult =
FunFile::getLines;
return listFiles(recurse).flatMap(
result -> result.map(onError, onResult)
);
}
 
Search WWH ::




Custom Search