Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Convert to try-with-resources" in Netbeans - Cool Beans?

Tags:

java

netbeans

I have the following code in Netbeans 7.1.2:

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filename));
bos.write(newRawData);
bos.close();

A warning suggests that I "convert to try-with-resources." When I choose to do this, my code becomes:

try (BufferedOutputStream bufferedFos = new BufferedOutputStream(new FileOutputStream(filename))) {
        bufferedFos.write(newRawData);
    }

This looks similar to the syntax for using(...) in C#... do they work the same way? Is there any downside to using this second format? I'm worried about the absence of bos.close();, but is it simply not necessary with this format?

like image 423
FreakinOutMan Avatar asked Jul 11 '12 20:07

FreakinOutMan


2 Answers

This was a new syntax that was introduced in Java 7, which takes care of closing any resources you specify when declaring the try(...) statement. More info can be found here.
So no, you don't have to do a bos.close(), it is performed by Java. You can just sit back and relax.
The only downside is that your code works with Java 7+ only.

like image 169
Keppil Avatar answered Nov 12 '22 03:11

Keppil


Note

The "try with resources" statement was introduced in Java 7 as a replacement for the try...finally statement. Basically, all it does is keep you from having to add:

finally {
  if(resource != null) resource.close();
}

to the end of your try statement. If you use this, your code will only work with Java 7 and up.

Answer

try is part of a statement in Java called try...catch. A full solution to the warning you were given would be:

try(BufferedOutputStream bufferedFos = new BufferedOutputStream(new FileOutputStream(filename))) {
  bufferedFos.write(newRawData);
} catch(FileNotFoundException e) {
  e.printStackTrace();
}

A "try with resources" block uses the same structure as the try...catch block, but automatically closes any resources that are created inside the block once it has been executed. That's why you don't see a bufferedFos.close(); statement in the code.

like image 31
Jon Egeland Avatar answered Nov 12 '22 04:11

Jon Egeland