Wednesday, February 6, 2013

Thanks god for ARM in java 7

One of the most disturbing thing that was exist in java was closing resources such files. first, you need to remember to close the file and put it finally since there is a chance that you will suffer from exception, but in the finally you have to protect yourself from getting null since the exception can happened in the creation of the stream or the channel. so the code should look like this:
      FileInputStream FileReader= null;
      FileOutputStream FileWriter = null;
      try {

        FileReader= new FileInputStream("in.txt");
        FileWriter = new FileOutputStream("out.txt");
        int var;
        while (var = != -1)
          FileWriter .write(var);
      } finally {
        if (FileReader!= null)
        if (FileWriter != null)
          FileWriter .close();

In addition, the close method throw exception as well so you need to handle it as well. This is very tricky code and very easy to make mistakes. no wonder spring provides useful templates for this issue. But from java 7 with automatic resource management we don't have to take care of it anymore. from java 7 you can write the same code like this:
try (
FileInputStream FileReader= new FileInputStream("in.txt");
FileOutputStream FileWriter = new FileOutputStream("out.txt")
) {
      int var;
      while((var= != -1 )
            FileWriter .write();
since OutputStream and InputStream implements the interface closeable with the method close, the close method will be called automatically if the object was created since the code is in try brackets. so now java take care the close of the file. I believe it will save a lot of time and many bugs mainly for novice programmers.

No comments: