The try-with-resources
statement is introduced in the Java 7. With this new statement we can simplify resource management in our program, also known as ARM (Automatic Resource Management).
This statement is a try
statement that declares one or more resources. After the program finish with the resource, it must be closed. The try-with-resources
ensures that each resource is closed and the end of the statement.
Any object that implements java.lang.AutoCloseable
, which includes all objects which implement java.io.Closeable
, can be used as a resource.
package org.kodejava.basic;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class TryWithResourceExample {
public static void main(String[] args) {
try {
TryWithResourceExample demo = new TryWithResourceExample();
demo.printStream("F:/tmp/data.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
private void printStream(String fileName) throws IOException {
char[] buffer = new char[1024];
try (InputStream is = new FileInputStream(fileName);
Reader reader = new BufferedReader(
new InputStreamReader(is, StandardCharsets.UTF_8))) {
while (reader.read(buffer) != -1) {
System.out.println(buffer);
}
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024