Uncategorized

Templates for Java 6 style resource management

I’ve seen so many questionable solutions of Java file and database IO that I decided to offer a template you can freely copy. By the way, being a hurried (and lazy) programmer, I frequently do Java IO wrong myself, so I will copy this template, too :).

Fortunately, Java 7 simplified file IO by adding automatic resource management, so this article is almost obsolete.

To read a file you can use the following code:

   public void readFile(String p_inputFileName) {
      FileReader file = null;
      BufferedReader buffer = null;
      try {
         file = new FileReader(p_inputFileName);
         buffer = new BufferedReader(file);
         /**** beginning of the business logic ******************************/
         int lines = 0;
         while (null != buffer.readLine()) {
            lines++;
         }
         System.out.println("The file consists of " + lines + " lines.");
         /**** end of the business logic ******************************/
      } catch (FileNotFoundException e) {
         System.out.println("The file does not exist.");
      } catch (IOException e) {
         System.out.println("An IO error occured." + e);
         e.printStackTrace();
      } finally {
         if (null != buffer)
            try {
               buffer.close();
            } catch (IOException e) {
               System.out.println("An IO error occured when closing the buffer." + e);
            }
         if (null != file)
            try {
               file.close();
            } catch (IOException e) {
               System.out.println("An IO error occured when closing the buffer." + e);
            }
      }
   }

Of course, this example is far from being perfect. Exception management is poor. The exceptions are treated within the function. This is sufficient in this example, but if you were to throw the exceptions to the calling method, you had to deal with the possibility of having two exceptions (the first one might be throw within the try block, and a second one might be thrown within the finally block). In reality, hardly anybody cares. It suffices to know there was an exception. However, Java 7 automatic resource management also deals with multiple exceptions.

There is a remarkable amount of boiler plate code. The business logic is limited to the five lines between the asterics. Wouldn’t it be nice to be able to use closures?

If you see any possibility to improve the algorithm, feel free to leave a comment so I can optimize my template.

Leave a Reply

Your email address will not be published.