5️⃣

14.5 Try-With-Resources

Try-With-Resources

In the last example, you had to close all your file streams explicitly in the finally block. Newer versions of Java have try-with-resources statements, where you specify which file/file streams you want to open, and then Java will automatically close them after the try/catch blocks.

Declare the file/file stream classes in parentheses () after the try keyword (don’t declare them separately outside of the block), and separate declarations with semicolons.

try (FileInputStream in = new FileInputStream(file);
    FileOutputStream out = new FileOutputStream("names_upper.txt")) {
           
	  int c;
    while ((c = in.read()) != -1) 
					out.write(Character.toUpperCase((char) c));

} catch (IOException e) {
    System.out.println("An IO Exception occurred.");
    e.printStackTrace(); // Prints error output stream.
}

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.