Java List.stream.forEach Lambda表达式内部未处理的IOException [英] Unhandled IOException Inside Java List.stream.forEach Lambda Expression

查看:308
本文介绍了Java List.stream.forEach Lambda表达式内部未处理的IOException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java 8中引入的Stream API来为列表中的每个字符串运行一个方法.

I am using the Stream API introduced in Java 8 to run a method for each string in a list.

public boolean initFile() throws IOException
{
    if (this.outFile.exists()) {
        this.outFile.delete();
    }
    return this.outFile.createNewFile();
}

public void writeStringToFile(String str, boolean addNewLine) throws IOException
{
    if (this.mode != FileMode.READ) {
        if (this.initFile()) {
            FileWriter fileWriter;
            if (this.mode == FileMode.APPEND)
                fileWriter = new FileWriter(outFile.getAbsolutePath(), true);
            else
                fileWriter = new FileWriter(outFile.getAbsolutePath());
            fileWriter.write(str);
            if (addNewLine)
                fileWriter.write("\n");
            fileWriter.close();
        } else {
            throw new IOException("IO Error: The file could not be initialized.");
        }
    } else {
        throw new IOException("Cannot write to a file with the mode FileMode.READ");
    }
}

public void writeListToFile(List<String> strings, boolean addNewLine) throws IOException
{
    strings.stream().forEach(s -> this.writeStringToFile(s, addNewLine)); // Unhandled IOException from writeStringToFile
}

如您所见,方法签名指出要抛出所有IOException,而流中的writeToString方法有可能抛出IOException.但是,Java编译器给我一个错误,指出在流线上存在未处理的IOException.

As you can see, the method signature states to throw all IOExceptions and the writeToString method inside the stream has the potential to throw an IOException. However, the Java compiler is giving me an error stating that there is an unhandled IOException on the stream line.

为什么流内的异常不会像方法内的任何其他异常一样抛出?我有什么办法可以在不将try-catch语句放入forEach lambda表达式中的情况下对此进行补救?

Why would the exception inside the stream not get thrown like any other exception inside the method? Is there any way that I can remedy this without putting a try-catch statement in the forEach lambda expression?

推荐答案

您必须在try writeListToFile方法中使用try catch:

you have to use try catch in you writeListToFile method like this:

  public void writeListToFile(List<String> strings, boolean addNewLine) throws Exception {
    strings.stream().forEach(s -> {
        try {
            writeStringToFile(s, addNewLine);
        } catch (IOException ex) {
            //you can Log it immediately or throw ex;
            Logger.getLogger(C.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    // Unhandled IOException from writeStringToFile
}

为什么? 看看这点s-> {}.这里{}表示编译器创建了新的Interface(Consumer)

why? look at this point s -> {}.Here {} means that compiler make new Interface (Consumer)

 void forEach(Consumer<? super T> action);

和新类实现此接口并将s参数传递给它的accept方法.您可以在方法中抛出新类的异常吗?不,所以您必须尝试捕获foreach的每一项

and new Class implements this interface and pass s parameter to it's accept method.Can you throw Exception of new Class in your method? No.So you have to try catch of every item of foreach

这篇关于Java List.stream.forEach Lambda表达式内部未处理的IOException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆