Java 9 try-with-resources Improvement
Java
207
java9
6
try-with-resources
2
Male avatar

loveprogramming viết ngày 19/04/2021

https://grokonez.com/java/java-9/java-9-try-resources-improvement

Java 9 try-with-resources Improvement

Java 7 introduces a new approach for closing resources by try-with-resources statement. After that, Java 9 try-with-resources makes an improved way of writing code. Now we can simplify our code and keep it cleaner and clearer.

Related post: Java 7 – try-with-resources Statement

1. Java 7 try-with-resources

This is the way we use it from Java 7:


try (BufferedReader br = new BufferedReader(new FileReader("C://readfile/input.txt"))) {
    String line;
    while (null != (line = br.readLine())) {
        // processing each line of file
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

It is good, but we have to declare the variable in try() block.
That's because we can't use resource which is declared outside the try() block within it. If resource is already declared outside, we should re-refer it with local variable:


// BufferedReader is declared outside try() block
BufferedReader br = new BufferedReader(new FileReader("C://readfile/input.txt"));

try (BufferedReader inBr = br) {
        // ...
    }
} catch (IOException e) {
    // ...
}

2. Java 9 try-with-resources improvement

Java 9 make things simple:

https://grokonez.com/java/java-9/java-9-try-resources-improvement

Java 9 try-with-resources Improvement

Bình luận


White
{{ comment.user.name }}
Bỏ hay Hay
{{comment.like_count}}
Male avatar
{{ comment_error }}
Hủy
   

Hiển thị thử

Chỉnh sửa

Male avatar

loveprogramming

451 bài viết.
79 người follow
Kipalog
{{userFollowed ? 'Following' : 'Follow'}}
Cùng một tác giả
Male avatar
1 0
Tutorial Link: (Link) (Ảnh) Django is a Pythonbased free and opensource web framework that follows the modeltemplateview architectural pattern. A...
loveprogramming viết 6 tháng trước
1 0
Male avatar
1 0
https://loizenai.com/angular11nodejspostgresqlcrudexample/ Angular 11 Node.js PostgreSQL Crud Example (Ảnh) Tutorial: “Angular 11 Node.js Postg...
loveprogramming viết 5 tháng trước
1 0
Male avatar
1 0
Angular Spring Boot jwt Authentication Example Github https://loizenai.com/angularspringbootjwt/ (Ảnh) Tutorial: ” Angular Spring Boot jwt Authe...
loveprogramming viết 5 tháng trước
1 0
Bài viết liên quan
Male avatar
0 0
https://grokonez.com/java/javaadvanced/java7trywithresourcesstatement Java 7 – trywithresources Statement Java 7 provides a new approach for clos...
loveprogramming viết 25 ngày trước
0 0
{{like_count}}

kipalog

{{ comment_count }}

bình luận

{{liked ? "Đã kipalog" : "Kipalog"}}


Male avatar
{{userFollowed ? 'Following' : 'Follow'}}
451 bài viết.
79 người follow

 Đầu mục bài viết

Vẫn còn nữa! x

Kipalog vẫn còn rất nhiều bài viết hay và chủ đề thú vị chờ bạn khám phá!