为了账号安全,请及时绑定邮箱和手机立即绑定

未处理异常的看似虚假的错误消息

未处理异常的看似虚假的错误消息

婷婷同学_ 2022-10-26 17:05:55
这是代码:import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.io.FileReader;import java.io.BufferedReader;import java.util.stream.Collectors;import java.io.FileWriter;import java.io.BufferedWriter;import java.util.List;public class CSVIO{    //read a file and return a list of records in the file    public static List<String[]> read(File f) throws IOException    {        BufferedReader br = new BufferedReader(new FileReader(f));        List<String[]> out = br.lines()                               .map( e -> e.split(","))                               .collect(Collectors.toList());        return out;    }    //write from a list of recrords into CSV format    public static void write(List<String[]> items, File dest) throws IOException    {        //return true if it successfully writes.            final BufferedWriter bw = new BufferedWriter(new FileWriter(dest));            items.stream()                 .map( row -> String.join(",",  row))                 .forEach( row  -> bw.write(row + "\n"));    }}我在运行时收到此错误消息:$ javac CSVIO.javaCSVIO.java:29: error: unreported exception IOException; must be caught or declared to be thrown                 .forEach( row  -> bw.write(row + "\n"));                                           ^1 error我已正确声明 write 方法会引发异常。有什么我想念的吗?
查看完整描述

1 回答

?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

问题是,你br.write()抛出了异常。您必须在 lambda 表达式 ( .forEach()) 中捕捉到这一点:


items.stream()

     .map(row -> String.join(",",  row))

     .forEach( row  -> {

         try {

             bw.write(row + "\n");

         } catch (IOException e) {

             e.printStackTrace();

         }

     });

但是您可以使用以下方法缩短它Files.write():


public static void write(List<String[]> items, Path path) throws IOException {

    List<String> lines = items.stream()

            .map(row -> String.join(",", row))

            .collect(Collectors.toList());

    Files.write(path, lines);

}

您还可以使用以下方法简化您的read方法Files.lines():


public static List<String[]> read(Path path) throws IOException {

    try (Stream<String> lines = Files.lines(path)) {

        return lines

                .map(e -> e.split(","))

                .collect(Collectors.toList());

    }

}


查看完整回答
反对 回复 2022-10-26
  • 1 回答
  • 0 关注
  • 68 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信