【问题标题】:Read and Write the files with try-with-resources [duplicate]使用 try-with-resources 读取和写入文件 [重复]
【发布时间】:2016-07-28 06:43:51
【问题描述】:

我想在同一个 try-with-resource 中读取和写入一个非常大的文件。做 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();
    }

【问题讨论】:

    标签: java-8 java-stream


    【解决方案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();
    }
    

    【讨论】:

    • 感谢@mtj,它有效但不利于可读性
    猜你喜欢
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多