001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.io;
016
017import com.google.common.annotations.Beta;
018import com.google.common.annotations.GwtIncompatible;
019import com.google.common.annotations.VisibleForTesting;
020import java.io.Closeable;
021import java.io.IOException;
022import java.io.InputStream;
023import java.io.Reader;
024import java.util.logging.Level;
025import java.util.logging.Logger;
026import javax.annotation.Nullable;
027
028/**
029 * Utility methods for working with {@link Closeable} objects.
030 *
031 * @author Michael Lancaster
032 * @since 1.0
033 */
034@Beta
035@GwtIncompatible
036public final class Closeables {
037  @VisibleForTesting static final Logger logger = Logger.getLogger(Closeables.class.getName());
038
039  private Closeables() {}
040
041  /**
042   * Closes a {@link Closeable}, with control over whether an {@code IOException} may be thrown.
043   * This is primarily useful in a finally block, where a thrown exception needs to be logged but
044   * not propagated (otherwise the original exception will be lost).
045   *
046   * <p>If {@code swallowIOException} is true then we never throw {@code IOException} but merely log
047   * it.
048   *
049   * <p>Example: <pre>   {@code
050   *
051   *   public void useStreamNicely() throws IOException {
052   *     SomeStream stream = new SomeStream("foo");
053   *     boolean threw = true;
054   *     try {
055   *       // ... code which does something with the stream ...
056   *       threw = false;
057   *     } finally {
058   *       // If an exception occurs, rethrow it only if threw==false:
059   *       Closeables.close(stream, threw);
060   *     }
061   *   }}</pre>
062   *
063   * @param closeable the {@code Closeable} object to be closed, or null, in which case this method
064   *     does nothing
065   * @param swallowIOException if true, don't propagate IO exceptions thrown by the {@code close}
066   *     methods
067   * @throws IOException if {@code swallowIOException} is false and {@code close} throws an
068   *     {@code IOException}.
069   */
070  public static void close(@Nullable Closeable closeable, boolean swallowIOException)
071      throws IOException {
072    if (closeable == null) {
073      return;
074    }
075    try {
076      closeable.close();
077    } catch (IOException e) {
078      if (swallowIOException) {
079        logger.log(Level.WARNING, "IOException thrown while closing Closeable.", e);
080      } else {
081        throw e;
082      }
083    }
084  }
085
086  /**
087   * Closes the given {@link InputStream}, logging any {@code IOException} that's thrown rather than
088   * propagating it.
089   *
090   * <p>While it's not safe in the general case to ignore exceptions that are thrown when closing an
091   * I/O resource, it should generally be safe in the case of a resource that's being used only for
092   * reading, such as an {@code InputStream}. Unlike with writable resources, there's no chance that
093   * a failure that occurs when closing the stream indicates a meaningful problem such as a failure
094   * to flush all bytes to the underlying resource.
095   *
096   * @param inputStream the input stream to be closed, or {@code null} in which case this method
097   *     does nothing
098   * @since 17.0
099   */
100  public static void closeQuietly(@Nullable InputStream inputStream) {
101    try {
102      close(inputStream, true);
103    } catch (IOException impossible) {
104      throw new AssertionError(impossible);
105    }
106  }
107
108  /**
109   * Closes the given {@link Reader}, logging any {@code IOException} that's thrown rather than
110   * propagating it.
111   *
112   * <p>While it's not safe in the general case to ignore exceptions that are thrown when closing an
113   * I/O resource, it should generally be safe in the case of a resource that's being used only for
114   * reading, such as a {@code Reader}. Unlike with writable resources, there's no chance that a
115   * failure that occurs when closing the reader indicates a meaningful problem such as a failure to
116   * flush all bytes to the underlying resource.
117   *
118   * @param reader the reader to be closed, or {@code null} in which case this method does nothing
119   * @since 17.0
120   */
121  public static void closeQuietly(@Nullable Reader reader) {
122    try {
123      close(reader, true);
124    } catch (IOException impossible) {
125      throw new AssertionError(impossible);
126    }
127  }
128}