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 org.checkerframework.checker.nullness.compatqual.NullableDecl;
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:
050   *
051   * <pre>{@code
052   * public void useStreamNicely() throws IOException {
053   *   SomeStream stream = new SomeStream("foo");
054   *   boolean threw = true;
055   *   try {
056   *     // ... code which does something with the stream ...
057   *     threw = false;
058   *   } finally {
059   *     // If an exception occurs, rethrow it only if threw==false:
060   *     Closeables.close(stream, threw);
061   *   }
062   * }
063   * }</pre>
064   *
065   * @param closeable the {@code Closeable} object to be closed, or null, in which case this method
066   *     does nothing
067   * @param swallowIOException if true, don't propagate IO exceptions thrown by the {@code close}
068   *     methods
069   * @throws IOException if {@code swallowIOException} is false and {@code close} throws an {@code
070   *     IOException}.
071   */
072  public static void close(@NullableDecl Closeable closeable, boolean swallowIOException)
073      throws IOException {
074    if (closeable == null) {
075      return;
076    }
077    try {
078      closeable.close();
079    } catch (IOException e) {
080      if (swallowIOException) {
081        logger.log(Level.WARNING, "IOException thrown while closing Closeable.", e);
082      } else {
083        throw e;
084      }
085    }
086  }
087
088  /**
089   * Closes the given {@link InputStream}, logging any {@code IOException} that's thrown rather than
090   * propagating it.
091   *
092   * <p>While it's not safe in the general case to ignore exceptions that are thrown when closing an
093   * I/O resource, it should generally be safe in the case of a resource that's being used only for
094   * reading, such as an {@code InputStream}. Unlike with writable resources, there's no chance that
095   * a failure that occurs when closing the stream indicates a meaningful problem such as a failure
096   * to flush all bytes to the underlying resource.
097   *
098   * @param inputStream the input stream to be closed, or {@code null} in which case this method
099   *     does nothing
100   * @since 17.0
101   */
102  public static void closeQuietly(@NullableDecl InputStream inputStream) {
103    try {
104      close(inputStream, true);
105    } catch (IOException impossible) {
106      throw new AssertionError(impossible);
107    }
108  }
109
110  /**
111   * Closes the given {@link Reader}, logging any {@code IOException} that's thrown rather than
112   * propagating it.
113   *
114   * <p>While it's not safe in the general case to ignore exceptions that are thrown when closing an
115   * I/O resource, it should generally be safe in the case of a resource that's being used only for
116   * reading, such as a {@code Reader}. Unlike with writable resources, there's no chance that a
117   * failure that occurs when closing the reader indicates a meaningful problem such as a failure to
118   * flush all bytes to the underlying resource.
119   *
120   * @param reader the reader to be closed, or {@code null} in which case this method does nothing
121   * @since 17.0
122   */
123  public static void closeQuietly(@NullableDecl Reader reader) {
124    try {
125      close(reader, true);
126    } catch (IOException impossible) {
127      throw new AssertionError(impossible);
128    }
129  }
130}