try-with-resources on arbitrary multiple files? (original) (raw)

Paul Sandoz paul.sandoz at oracle.com
Tue Apr 22 08:47:23 UTC 2014


On Apr 22, 2014, at 3:18 AM, Wang Weijun <weijun.wang at oracle.com> wrote:

If I copy a file to another I can

try (src = open(ifile); dest = open(ofile)) { while (!src.EOF) dest.write(src.read()); } but what if there are multiple destinations? Is there something like

Not that i am aware of.

A fun little trick you can do is the following:

    File ifile = null;
    List<OutputStream> dests = new ArrayList<>();
    try (InputStream src = open(ifile); AutoCloseable ac = () -> closeAll(dests)) {
       dests.add(...);
        ....
    }

static void closeAll(Collection<? extends OutputStream> l) throws IOException {
    ...
}

But still that does not avoid the main work of closing stuff.

Paul.

try (src = open(ifile); manager = new CloseableManager()) { for (ofile: ofiles) { manager.register(open(ofile)); } while (!src.EOF) { buffer = src.read(); for (dest: manager) dest.write(buffer); } }

Thanks Max



More information about the core-libs-dev mailing list