30 November 2017

try-with-resources

A known, and now kind of old feature of Java 7, but still isn't as popular as we wish.

Straightforward (and easy) implementation, where you need to declare resources (File, Stream) into parenthesis of "try" keyword:

private static void printFileJava7() throws IOException {

    try(InputStream input = new FileInputStream("hola.txt")) {

        int data = input.read();
        while(data != -1){
            System.out.print((char) data);
            data = input.read();
        }
    }
}

And JVM will have the responsibility to close those resources.

Beware: that the object in try() must implement AutoCloseable.

More info:

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

http://tutorials.jenkov.com/java-exception-handling/try-with-resources.html

https://www.mkyong.com/java/try-with-resources-example-in-jdk-7/


No comments :

Blog Archive

Disclaimer

The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.