How to work with streams properly since Java 7

How to work with streams properly since Java 7 using try-with-resources block.

How to handle exceptions properly since Java 7? You can still use the classic way, or you can use the new try-with-resources block. After try block put parenthesis and inside open stream. After this block closes, the stream will be automatically closed as well. To handle exceptions add catch block.

try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String line = null;
while ((line = reader.readLine()) != null) {
} catch (IOException ex) {

comments powered by Disqus


Free online Java web application examples

Want to develop whole web applications which use database, security and more? See my github account, where are lot's of example projects: