4

New to Java 8 and practicing Streams and Lambdas.

I am trying to create a Stream<String> out of a folder files content. This is something that I tried unsuccessfully:

Stream<String> lineStream = Files.walk(Paths.get("resources")).flatMap(Files::lines);

The compiler yells that I am not catching an IOException even if I have a throws clause. Can anyone explain this to me?

I managed to print all the files that I am interested in with the following:

Files.walk(Paths.get("resources"))
    .map(Path::toFile)
    .filter(File::isFile)
    .forEach(System.out::println);

How do I get a Stream<String> with each String being a line of the files printed by the code above?

Holger
  • 285,553
  • 42
  • 434
  • 765
Marsellus Wallace
  • 17,991
  • 25
  • 90
  • 154
  • See also this question: [Mandatory checked exceptions handling in lambda expressions for standard Java 8 functional interfaces](http://stackoverflow.com/questions/14039995). – Stuart Marks Sep 22 '14 at 05:17
  • 1
    DO NOT CLOSE IT! Besides the lambda expression throwing a checked exception, is this the best way to concatenate streams from multiple files? Is there a more concise way? What if some files are folders? – Marsellus Wallace Sep 22 '14 at 21:25
  • As it stands the question is mostly about dealing with `IOException`, which seems well covered by the other questions and answers. If you have additional questions, you can edit this one to be more specific, or just ask a different question. – Stuart Marks Sep 23 '14 at 05:17
  • @Gevorg: yes, `flatMap` is a proper way of concatenating streams. To pre-filter the stream of `Path`s, you should get to know about [`Files::isRegularFile`](http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#isRegularFile-java.nio.file.Path-java.nio.file.LinkOption...-) – Holger Sep 25 '14 at 08:48
  • `List rowList = paths.filter(Files::isRegularFile) .flatMap(a -> { try { return Files.lines(a); } catch (IOException e) { throw new UncheckedIOException(e);}}) .collect(Collectors.toList());` – Haha TTpro Apr 20 '18 at 09:09

0 Answers0