From the course: Java 11+ Essential Training

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Close objects with try-with-resources

Close objects with try-with-resources - Java Tutorial

From the course: Java 11+ Essential Training

Start my 1-month free trial

Close objects with try-with-resources

- [Instructor] There are certain kinds of objects that you'll want to work with in try-catch blocks that need special handling. These are objects that you open for some purpose and then have to close to make sure you're not leaking memory. For most java developers, the first time you'll encounter this is when you start working with files. In this beginning application, I've added a text file to the project's root directory. It's named hello.txt, and it contains just a single line of text. I want to read that file into memory. I've created an instance of the java file class that references that file and I have a bit of code here that indicates whether I can find the file successfully. When I run the starting code, I get a message saying that the file exists, so so far so good. Now to read the contents of the file, I'll create two objects. The first is called a file reader. I'll name it reader, and I'll initialize…

Contents