The Java 7 try-with-resources Statement PRO

As of Java 7 we can code a try statement that declares one or more resources. Each resource is an object that must be closed after the program is finished. The try-with-resources statement ensures that each resource is closed at the end of the statement. Each object considered as a resource must be instantiated from a class that implements java.lang.AutoCloseable.

package com.abelski.samples;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TryResourcesDemo
{
	public static void main(String[] args)
	{
		try
		{
			String str = readTextFile("bb.txt");
			System.out.println(str);
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}

	static String readTextFile(String path) throws IOException 
	{
		StringBuilder builder = new StringBuilder();
		try (BufferedReader br = new BufferedReader(new FileReader(path))) 
		{
			String str = null;
			while((str = br.readLine())!=null)
			{
				builder.append(str).append("\n");				
			}
		}
		return builder.toString();
	}
}

The following video clips shoes the execution of this code sample and explains it.

Share:

banner for the css playlist in hebrew life michael courses for programmers

The First Steps in CSS

Learn CSS using our our videos (in Hebrew) on the CSS (he) playlist on youtube. Do it now. Do it for free.

Good Trainers Collaborate with Others

It is always essential to keep an open mind and learn from others. This applies to everyone, including teachers and especially software development trainers. Software

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Update cookies preferences