Search This Blog

Java: Avoid nested streams in try-with-resources

Using nested streams in try-with-resources assuming all levels of streams are opened successfully. This is not always true. For example,
// DO NOT DO THIS. It may cause resource leaks.
try (BufferedWriter bw = new BufferedWriter(
        new OutputStreamWriter(
        new GZIPOutputStream(
        new FileOutputStream(f))))) {
    // ...
}
The constructor of GZIPOutputStream could throw an excpeiton, in which case, it will leave the FileOutputStream open. So according to try-with-resources tutorial, you should do below instead:
try (
    OutputStream os = new FileOutputStream(f);
    GZIPOutputStream gos = new GZIPOutputStream(os);
    OutputStreamWriter osw = new OutputStreamWriter(gos);
    BufferedWriter bw = new BufferedWriter(osw)
    ) {
    // ...
}
And it will close all the resources(streams,writers) in the opposite order of their creation.




see also

No comments:

Post a Comment