1

I want to read and write in the same try-with-resource for a very large file. Do try-with-resource take care of the exceptions thrown with in the its body.

try (Stream<String> stream = Files.lines(Paths.get("source.txt"), Charset.defaultCharset());
            BufferedWriter writer = Files.newBufferedWriter(Paths.get("dest.txt"))) {
        stream.map(String::trim).map(String::toUpperCase).forEach(writer::write);
    } catch (Exception e) {
        e.printStackTrace();
    }
ravthiru
  • 8,878
  • 2
  • 43
  • 52

1 Answers1

1

The lambda cannot cope with the checked exception that way (write::write throws IOException)

Unfortunately, to use this in a stream, you'll have to wrap it in the lambda which is quite ugly:

try (
   Stream<String> stream = Files.lines(Paths.get("source.txt"), Charset.defaultCharset());
   BufferedWriter writer = Files.newBufferedWriter(Paths.get("dest.txt"))) {
   stream.map(String::trim)
     .map(String::toUpperCase)
     .forEach(s -> {
        try {
           writer.write(s);
        } catch(IOException e) {
           throw new RuntimeException(e);
        }
     });
} catch (Exception e) {
    e.printStackTrace();
}
mtj
  • 3,381
  • 19
  • 30