使用try-with-resources读取和写入文件

时间:2016-07-28 06:43:52

标签: java-8 java-stream

我想在一个非常大的文件中使用相同的try-with-resource进行读写。尝试使用资源来处理在其正文中抛出的异常。

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();
    }

1 个答案:

答案 0 :(得分:1)

lambda无法应对检查过的异常(write :: write抛出IOException)

不幸的是,要在流中使用它,你必须将它包装在非常难看的lambda中:

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();
}