From 567637497c5aac2dc21c1946c74c246fe070d9f6 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 14 Oct 2024 16:04:07 -0500 Subject: [PATCH] Add Ensure Resources Always Get Closed as a Java TIL --- README.md | 3 +- java/ensure-resources-always-get-closed.md | 55 ++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 java/ensure-resources-always-get-closed.md diff --git a/README.md b/README.md index 7ba7bc6..bc2b30f 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1466 TILs and counting..._ +_1467 TILs and counting..._ --- @@ -442,6 +442,7 @@ _1466 TILs and counting..._ ### Java +- [Ensure Resources Always Get Closed](java/ensure-resources-always-get-closed.md) - [Install Java On Mac With Brew](java/install-java-on-mac-with-brew.md) - [Run A Hello World Program In Eclipse](java/run-a-hello-world-program-in-eclipse.md) diff --git a/java/ensure-resources-always-get-closed.md b/java/ensure-resources-always-get-closed.md new file mode 100644 index 0000000..2882e1c --- /dev/null +++ b/java/ensure-resources-always-get-closed.md @@ -0,0 +1,55 @@ +# Ensure Resources Always Get Closed + +Java has a construct known as _try-with-resource_ that allows us to always +ensure opened resources get closed. This is safer than similar cleanup in the +`finally` block which could still leave a memory leak if an error occurs in +that block. + +To use the _try-with-resource_ construct, instantiate your opened resource in +parentheses with the `try`. + +```java +try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { + // ... +} +``` + +The resource will be automatically closed when the try/catch block completes. + +Here is a full example: + +```java +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class FileReaderExample { + public static void main(String[] args) { + String fileName = "example.txt"; + + try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { + String line; + int lineCount = 0; + + while ((line = reader.readLine()) != null && lineCount < 5) { + System.out.println(line); + lineCount++; + } + } catch (IOException e) { + System.out.println("An error occurred while reading the file: " + e.getMessage()); + } + } +} +``` + +You can even specify multiple resources in one `try`. The above does that, but +this will make it more obvious: + +```java +try (FileReader fr = new FileReader(filename); + BufferedReader br = new BufferedReader(fr)) { + // ... +} +``` + +[source](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)