Java 8 Read File With try-with-resources

You might have noticed that In the previous post about files we have not closed any file stream. Streams implement AutoCloseable and in this case, we need to close stream explicitly. We can use try-with-resources to close the stream.

Sample Code

Close BufferedReader
1
2
3
4
5
6
7
8
9
10
11
12

public static void main(String[] args) throws IOException {
String filePath = "C:\\data\\demo\\sample.txt";
try(BufferedReader reader = Files.newBufferedReader(Paths.get(filePath)))
{
reader.lines().forEach(System.out::println);
}
catch (Exception e) {
// TODO: handle exception
}
}

Close Stream
1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) throws IOException {
String filePath = "C:\\data\\demo\\sample.txt";
try(Stream<String> lines = Files.lines(Paths.get((filePath))))
{
lines.forEach(System.out::println);

}
catch (Exception e) {
// TODO: handle exception
}
}
Share Comments