Los resources son objetos que deber ser cerrados despues que se terminaron de utilizar. Pomemos mencionar a InputStream o OutputStream como ejemplos de resources.
Para cerrar un InputStream debemos escribir el siguiente código:
InputStream in = null; try { in = new FileInputStream(new File("/tmp/prueba.txt")); ... } catch(Exception e) { ... } finally { if(in != null) { in.close(); } }
La sentencia try-with-resources nos permitira cerrar automaticamente los resources declarados.
try (InputStream in = new FileInputStream(new File("/tmp/prueba.txt"))) { byte[] buf = new byte[1024]; in.read(buf); System.out.println(buf); }
Solamente las clases que implementan la interface AutoCloseable pueden ser cerradas automaticamentes cuando se declaran en un try-with-resources.
Clases que implementan AutoCloseable
- InputStream
- OutputStream
- Reader
- Writer
- Connection
- Statement
- ResultSet
Para más información:
http://download.java.net/jdk7/docs/technotes/guides/language/try-with-resources.html

