Java Stream Close close(Closeable resource)

Here you can find the source of close(Closeable resource)

Description

Check if the given resource is not null and then close it, whereby any caught IOException is been returned instead of thrown, so that the caller can if necessary handle (log) or just ignore it without the need to put another try-catch.

License

Apache License

Parameter

Parameter Description
resource The closeable resource to be closed.

Return

The caught , or null if none is been thrown.

Declaration

public static IOException close(Closeable resource) 

Method Source Code

//package com.java2s;
/*//from   www  . j a v  a2s. c o m
 * Copyright 2013 OmniFaces.
 *
 * 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.
 */

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

public class Main {
    /**
     * Check if the given resource is not <code>null</code> and then close it, whereby any caught {@link IOException}
     * is been returned instead of thrown, so that the caller can if necessary handle (log) or just ignore it without
     * the need to put another try-catch.
     * @param resource The closeable resource to be closed.
     * @return The caught {@link IOException}, or <code>null</code> if none is been thrown.
     */
    public static IOException close(Closeable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                return e;
            }
        }

        return null;
    }
}

Related

  1. close(Closeable closeable, boolean swallowIOException)
  2. close(Closeable closeable, Logger logger)
  3. close(Closeable io, Logger logger)
  4. close(Closeable resource)
  5. close(Closeable resource)
  6. close(Closeable resource, File file)
  7. close(Closeable stream)
  8. close(Closeable... streams)
  9. close(Collection inCloseables)