AI Hints
Home›Java Tutorial›Checked and Unchecked, throw and Custom Exceptions, try-with-resources
Java · Lesson 96 of 120

try-with-resources

Close things automatically.

⏱ 2 min read▶ Video at 2:01:49🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Files, and network connections, must be closed when you're done. Otherwise, data might not be saved, or the system runs out of handles. Try with resources closes them for you.

  • Files must be closed
  • Easy to forget
  • Closed automatically

Writing and reading safely

The resource goes in round brackets, right after try. Here, a print writer, writing to log dot text. When the block ends, Java closes it automatically, even if an exception happens. The second block reads the file back, line by line. Read line returns null at the end of the file. Run it. Both lines are written, and read back.

Main.javajava
import java.io.*;
public class Main {
    public static void main(String[] args) throws IOException {
        try (PrintWriter out = new PrintWriter(new FileWriter("log.txt"))) {
            out.println("first line");
            out.println("second line");
        }
        try (BufferedReader in = new BufferedReader(new FileReader("log.txt"))) {
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println("Read: " + line);
            }
        }
    }
}
Output
Read: first line
Read: second line

Why it matters

Before Java seven, people closed files in finally blocks, which was long and easy to get wrong. Try with resources is shorter, and always correct. Use it for anything that needs closing.

keyvalue
try ( resource )opened here
End of blockclosed automatically
Even on errorstill closed
Use forfiles, connections, scanners

Summary

Put a resource in brackets after try, and Java closes it automatically, even after an error. Next, writing files.

Key takeaways
  • try (Resource r = …)
  • Auto-closed
  • Even on errors
Next up: Writing Files — save data to disk