Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java code style for open stream try/finally block [duplicate]

This is a code style question. I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:

InputStream in = null;
try {
    in = acquireStream();
    ...
} finally {
    if (in != null) in.close();
}

Note the initialization to null and check for null in the finally block.

I tend to write code like this:

InputStream in = acquireStream();
try {
    ...
} finally {
    in.close();
}

Are there advantages or disadvantages to either approach? I like my style because I don't need the null check. Also I like to avoid null when possible. But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.

I ask the same question for InputStream, OutputStream, java.sql.Connection, java.sql.PreparedStatement, etc. I tend to acquired the resource outside the try block and then close it in finally without a null check. Is there anything I am missing other than stylistic differences?

Thanks.

like image 310
Patrick Avatar asked Jan 18 '11 18:01

Patrick


1 Answers

Since Java 7 there is a much nicer way to write try-finally block in regards to Closeable resources.

Now you can create your resources in parenthesis after the try keyword, like this:

try (init resources) {
   ...
}

And they will be closed automcatically after the block of code is finished. There is no need to close the streams in finally block.

An example:

try (
   ZipFile zf = new ZipFile(zipFileName);
   BufferedWriter writer = Files.newBufferedWriter(outputFilePath, charset);
) {
    // Enumerate each entry
    for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
        // Get the entry name and write it to the output file
        String newLine = System.getProperty("line.separator");
        String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;
        writer.write(zipEntryName, 0, zipEntryName.length());
    }
}

And after the for loop is done, the resources will be closed!

like image 113
darijan Avatar answered Oct 05 '22 13:10

darijan