Java 17 Recipes


-13. Handling try-with-resources Construct


Download 3.2 Mb.
Pdf ko'rish
bet44/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   40   41   42   43   44   45   46   47   ...   245
Bog'liq
Java 17 Recipes

2-13. Handling try-with-resources Construct
 Problem
You’d like to easily manage the closing of effectively final variables.
 Solution
The try-with-resources construct was introduced in Java 7, allowing easy resources 
management. It became even easier in the Java 9 version because there is no need to 
effectively create a new variable for the sake of the construct. In the following code, the 
writeFile() method takes a BufferedWriter as an argument, and since it is passed into 
the method and ready to use, it is effectively final. This means it can simply be listed in 
the try-with-resources rather than creating a new variable.
public static void main(String[] args) {
try {
writeFile(new BufferedWriter(
new FileWriter("Easy TryWithResources")),
"This is easy since Java 9");
} catch (IOException ioe) {
System.out.println(ioe);
}
}
public static void writeFile(BufferedWriter writer, String text) {
try (writer) {
writer.write(text);
} catch (IOException ioe) {
System.out.println(ioe);
}
}
This code creates a new file named EasyTryWithResources. It adds the “This is easy 
in Java 9” text.
Chapter 2 enhanCements from Java 9 through Java 17 


72
 How It Works
The try-with-resources construct has become even easier with Java 9 and allows one 
to handle the opening and closing of resources very easily. If we have a resource, such as 
a database connection or a BufferedStream, it is good to manage wisely. In other words, 
open the resource, then use it accordingly, and finally close the resource when finished 
to ensure no resource leaks. The try-with-resources construct allows one to open a 
resource within the try block and have it automatically cleaned up once it completes.
The solution was shown in Java 9. It is possible to simply begin using a resource 
within a try-with-resources construct if it is passed into a method as an argument 
or a final field. While this is not a major language change, it certainly makes handling 
resources a bit easier, making the try-with-resources block even easier to understand.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   40   41   42   43   44   45   46   47   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling