2

I have a list of OutputStream to deal with, and I know when I only need one, I can make sure it is closed using try-with-resources pattern, like:

try(OutputStream os = new ByteArrayOutputStream()) {
    do something...
} catch (IOException e) {
    do something...
}

But what if there is a list of them? Can I just put the list(ArrayList or normal array) in the parentheses after try?

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Elderry
  • 1,902
  • 5
  • 31
  • 45
  • There's no explicit support for `List` in try-with-resource statements. If you really want to use `try (...) { ... }` syntax, you'll have to roll your own `AutoCloseable` that wraps a list of `AutoCloseables`. Something like [this](http://pastebin.com/8MtLFLu2) could work. – aioobe May 19 '16 at 13:30

1 Answers1

2

You could use the foreach (or the standard for) for this purpose.

OutputStream[] streams = {...};

for (OutputStream stream : streams) {
    try (OutputStream os = stream) {} 
    catch (IOException e) {}
}

You cannot "put ArrayList or normal array in the parentheses after try", because it can work only with objects which implement the interface java.lang.AutoCloseable.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142