Open source java code style try / finally block

See English answers > java IO ugly try finally block12

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

Note that the initialization is null, and check for null in the finally block

I prefer to write the following code:

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

Do both methods have advantages? I like my style because I don't need an empty check I also want to avoid null as much as possible However, since Oracle style is very common in network examples, I want to know if there are some hidden errors in my

I am interested in InputStream, OutputStream, Java sql. Connection,java. sql. Preparedstatement et al. Raised the same question I tend to get resources outside the try block and finally close it without null checking Apart from the stylistic differences, is there anything else I'm missing?

thank you.

Solution

Because Java 7 has a better way to write try finally blocks about closeable resources

You can now create resources in parentheses after the try keyword, as follows:

try (init resources) {
   ...
}

When the code blocks are complete, they will close automatically It is not necessary to close the flow in the final 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,zipEntryName.length());
    }
}

After the for loop is completed, the resource will be closed!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>