Learn Java Tutorial for Beginners (Video), Part 40: Try With Resources

Java 7 introduces a great new language feature, "try with resources". In this tutorial we'll see how we can use a try block to simply our file reading code quite a lot, ensuring that file handles are closed without the need of a hideous nested try block or a finally clause. We'll also look at AutoCloseable.

When the video is running, click the maximize button in the lower-right-hand corner to make it full screen.



Code for this tutorial:

App.java:

 

class Temp implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println("Closing!");
        throw new Exception("oh no!");
    }
    
}


public class App {

    public static void main(String[] args) {
        
        try(Temp temp = new Temp()) {
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }

}

 

App2.java:

 

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

public class App2 {

    public static void main(String[] args) {
        File file = new File("test.txt");

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;

            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            System.out.println("Can't find file " + file.toString());
        } catch (IOException e) {
            System.out.println("Unable to read file " + file.toString());
        }

    }

}