forked from rahulXbarnwal/JavaTutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLearningTryWith.java
More file actions
36 lines (32 loc) · 1.22 KB
/
LearningTryWith.java
File metadata and controls
36 lines (32 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package exceptions;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
// BufferedReader is using system resources which needs to be closed
// to make sure its closed, we can use finally block
public class LearningTryWith {
public static void main(String[] args) {
// BufferedReader reader = null;
// try {
// reader = new BufferedReader(new FileReader("example.txt"));
// object which will be created inside the parenthesis, will get auto closed
// - only the objects of class which is implementing AutoClosable interface
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("IOException caught: " + e.getMessage());
}
// finally {
// try {
// if (reader != null) {
// reader.close();
// }
// } catch (IOException e) {
// System.out.println("Error closing reader: " + e.getMessage());
// }
// }
}
}