How to use Try-with-resources with if statement?

余生长醉 提交于 2020-01-04 04:16:25

问题


I have the simple code:

try (FileReader file = new FileReader(messageFilePath);
     BufferedReader reader = new BufferedReader(file)) {

    String line;

    while ((line = reader.readLine()) != null) {
        ////
    }
} 

I want to write something like that:

FileReader file = null;
///.....

try(file = (file == null ? new FileReader(messageFilePath) : file);
     BufferedReader reader = new BufferedReader(file)) {

    String line;

    while ((line = reader.readLine()) != null) {
        ////
    }
} 

It is allows me to reuse FileReader. Is it possible? If not, how to correctly reuse FileReader? I use java 8, if it is important.


回答1:


You always have to define a new variable part of try-with-resources block. It is the current limitation of the implementation in Java 7/8. In Java 9 they consider supporting what you asked for natively.

You can however use the following small trick:

public static void main(String[] args) throws IOException {
    FileReader file = null;
    String messageFilePath = "";

    try (FileReader reader = file = (file == null ? new FileReader(messageFilePath) : file);
            BufferedReader bufReader = new BufferedReader(file)) {

        String line;

        while ((line = bufReader.readLine()) != null) {
            ////
        }
    }
}


来源:https://stackoverflow.com/questions/28702219/how-to-use-try-with-resources-with-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!