Try-with-Resources in Java


Try-with-resources automatically manages resource closure, reducing the risk of resource leaks.

Source Code

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments