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.
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.
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.
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.
The close() method of objects declared in a try with resources block is invoked regardless of whether an exception is thrown during execution.
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) {
////
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With