From the course: Advanced Java Programming

Unlock the full course today

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

Using try-with-resources with I/O

Using try-with-resources with I/O - Java Tutorial

From the course: Advanced Java Programming

Start my 1-month free trial

Using try-with-resources with I/O

- [Instructor] When using input and output resources, it is important to use try with resources whenever you can. Using try with resources makes sure that all resources are closed for me. I don't have to worry about manually closing all resources which can be difficult. If resources aren't closed properly, it is easy to end up with code-leaking resources. This is especially true if you are using multiple resources that interact with each other. In this example, I have a class called TryWithResourcesExample. Inside the main method, I have a buffered reader wrapped around a string reader, which just takes a simple string containing Hello World. I then have a simple string writer called writer. Next, I call writer.write, and inside that method, I call reader.readLine so I am using a reader to read a string and then I'm writing it to a writer. Finally, I print out the result. When I run the program, I get the simple Hello World message printed to the console. I have wrapped all of my code…

Contents