Languages
[Edit]
EN

Java - try with resources

0 points
Created by:
Dirask Community
6810

In this article, we would like to show you how to use try with resources in Java.

Below we present a comparison of two solutions:

  • try-with-resources,
  • try with finally block.

1. Using try-with-resources

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

public class Example {

    public static void main(String[] args) {
        String path = "C:\\path\\example.txt";

        try (BufferedReader br = new BufferedReader(new FileReader(path))) {
            System.out.println(br.readLine());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. Using try with finally block instead

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

public class Example {

    public static void main(String[] args) throws IOException {
        String path = "C:\\path\\example.txt";

        BufferedReader br = new BufferedReader(new FileReader(path));
        try {
            System.out.println(br.readLine());

        } finally {
            br.close();
        }
    }
}

References

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join