org.chiefly.nautilus.Closeables.java Source code

Java tutorial

Introduction

Here is the source code for org.chiefly.nautilus.Closeables.java

Source

// Copyright (C) 2015 chief8192@gmail.com
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

package org.chiefly.nautilus;

import java.io.Closeable;
import java.io.IOException;

import com.google.common.base.Preconditions;

/** Utility methods for {@link Closeable}s. */
public class Closeables {

    /** Private default constructor. */
    private Closeables() {
        throw new UnsupportedOperationException();
    }

    /**
     * @param closeables The {@link Closeable}s to be closed.
     * @throws IOException if an I/O error occurs.
     */
    public static void closeAll(final Closeable... closeables) throws IOException {

        /* Arguments checks */
        Preconditions.checkNotNull(closeables);
        if (closeables.length == 0) {
            return;
        }

        /* Start closing */
        closeAll(0, closeables);
    }

    /**
     * @param index The index of the current {@link Closeable} to close.
     * @param closeables The {@link Closeable}s to be closed.
     * @throws IOException if an I/O error occurs.
     */
    private static void closeAll(final int index, final Closeable... closeables) throws IOException {

        /* Arguments checks */
        if ((index < 0) || (index >= closeables.length)) {
            throw new IllegalArgumentException();
        }

        try {

            /* Try to close the current Closeable */
            final Closeable closeable = closeables[index];
            if (closeable != null) {
                closeable.close();
            }

        } finally {

            /* Recurse if needed */
            if ((index + 1) < closeables.length) {
                closeAll(index + 1, closeables);
            }
        }
    }
}