简体   繁体   中英

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

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 this:

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

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

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

It would allow me to reuse FileReader . Is it possible? If not, how to correctly reuse FileReader ?

PS
I use Java 8, if it is important.

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) {
            ////
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM