logo

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) {
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}

comments powered by Disqus

rss

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:
github

Search