EN
Java - try with resources
0 points
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
withfinally
block.
xxxxxxxxxx
1
import java.io.BufferedReader;
2
import java.io.FileReader;
3
import java.io.IOException;
4
5
public class Example {
6
7
public static void main(String[] args) {
8
String path = "C:\\path\\example.txt";
9
10
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
11
System.out.println(br.readLine());
12
13
} catch (IOException e) {
14
e.printStackTrace();
15
}
16
}
17
}
xxxxxxxxxx
1
import java.io.BufferedReader;
2
import java.io.FileReader;
3
import java.io.IOException;
4
5
public class Example {
6
7
public static void main(String[] args) throws IOException {
8
String path = "C:\\path\\example.txt";
9
10
BufferedReader br = new BufferedReader(new FileReader(path));
11
try {
12
System.out.println(br.readLine());
13
14
} finally {
15
br.close();
16
}
17
}
18
}