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

这是代码:


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.java

CSVIO.java:29: error: unreported exception IOException; must be caught or declared to be thrown

                 .forEach( row  -> bw.write(row + "\n"));

                                           ^

1 error

我已正确声明 write 方法会引发异常。有什么我想念的吗?


婷婷同学_
浏览 89回答 1
1回答

Smart猫小萌

问题是,你br.write()抛出了异常。您必须在 lambda 表达式 ( .forEach()) 中捕捉到这一点:items.stream()&nbsp; &nbsp; &nbsp;.map(row -> String.join(",",&nbsp; row))&nbsp; &nbsp; &nbsp;.forEach( row&nbsp; -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;bw.write(row + "\n");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;});但是您可以使用以下方法缩短它Files.write():public static void write(List<String[]> items, Path path) throws IOException {&nbsp; &nbsp; List<String> lines = items.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(row -> String.join(",", row))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());&nbsp; &nbsp; Files.write(path, lines);}您还可以使用以下方法简化您的read方法Files.lines():public static List<String[]> read(Path path) throws IOException {&nbsp; &nbsp; try (Stream<String> lines = Files.lines(path)) {&nbsp; &nbsp; &nbsp; &nbsp; return lines&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(e -> e.split(","))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java