Try with Resources
Developers who have used sonar for code analysis would have seen this check Try-with-resources should be used. Try-with-resources statement was introduced in Java 7 which guarantees that the resources will be closed. Lets see this in detail using the below example.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
private static String fileName = "D:\\proverbs.txt";
public static void main(String args[]) {
readFile(fileName);
}
private static void readFile(String fileName) {
File file = new File(fileName);
try (FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the above code we could see logic to read a file and print its contents. For reading the file we have used FileReader and BufferedReader which are classes that implement Closeable interface which has method close used to close the stream.
package java.io;
import java.io.IOException;
/**
* A {@code Closeable} is a source or destination of data that can be closed.
* The close method is invoked to release resources that the object is
* holding (such as open files).
*
* @since 1.5
*/
public interface Closeable extends AutoCloseable {
/**
* Closes this stream and releases any system resources associated
* with it. If the stream is already closed then invoking this
* method has no effect.
*
* <p> As noted in {@link AutoCloseable#close()}, cases where the
* close may fail require careful attention. It is strongly advised
* to relinquish the underlying resources and to internally
* <em>mark</em> the {@code Closeable} as closed, prior to throwing
* the {@code IOException}.
*
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException;
}
When we create the classes which implement Closeable interface using try-with-resources the close methods of these objects are automatically called either the flow terminates normally or with an exception.
Leave a Reply