logo

How to properly structure a method for accessing a file (pre Java 7 style)

How to properly structure a method for accessing a file (pre Java 7 style) using try-catch-finally block.

How to handle exceptions? It would be really bad if you didn't close the files properly. Such situation can easily happen in this code. I will now show you how to properly structure this method. Be aware that this is pre-Java 7 style. Since Java 7 you can do that in a much easier way.

BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.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