Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

P.S.
I use Java 8, if it is important.

like image 726
Denis Avatar asked Feb 24 '15 17:02

Denis


People also ask

How do you try with resources?

The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.

Can we use try with resources without catch and finally?

Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System. exit() it will execute always.

How do you catch exceptions in try with resources?

You can add a catch block to a try-with-resources block just like you can to a standard try block. If an exception is thrown from within the try block of a try-with-resources block, the catch block will catch it, just like it would when used with a standard try construct.

Does try with resources close on exception?

The close() method of objects declared in a try with resources block is invoked regardless of whether an exception is thrown during execution.


1 Answers

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) {
            ////
        }
    }
}
like image 196
Crazyjavahacking Avatar answered Nov 01 '22 20:11

Crazyjavahacking