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.GwtIncompatible;
018import com.google.common.annotations.J2ktIncompatible;
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.jspecify.annotations.Nullable;
027
028/**
029 * Utility methods for working with {@link Closeable} objects.
030 *
031 * @author Michael Lancaster
032 * @since 1.0
033 */
034@J2ktIncompatible
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  /*
073   * The proper capitalization would be "swallowIoException." However:
074   *
075   * - It might be preferable to be consistent with the JDK precedent (which they stuck with even
076   *   for "UncheckedIOException").
077   *
078   * - If we change the name, some of our callers break because our Android Lint ParameterName check
079   *   doesn't make the exception for com.google.common that internal Error Prone does: b/386402967.
080   */
081  @SuppressWarnings("IdentifierName")
082  public static void close(@Nullable Closeable closeable, boolean swallowIOException)
083      throws IOException {
084    if (closeable == null) {
085      return;
086    }
087    try {
088      closeable.close();
089    } catch (IOException e) {
090      if (swallowIOException) {
091        logger.log(Level.WARNING, "IOException thrown while closing Closeable.", e);
092      } else {
093        throw e;
094      }
095    }
096  }
097
098  /**
099   * Closes the given {@link InputStream}, logging any {@code IOException} that's thrown rather than
100   * propagating it.
101   *
102   * <p>While it's not safe in the general case to ignore exceptions that are thrown when closing an
103   * I/O resource, it should generally be safe in the case of a resource that's being used only for
104   * reading, such as an {@code InputStream}. Unlike with writable resources, there's no chance that
105   * a failure that occurs when closing the stream indicates a meaningful problem such as a failure
106   * to flush all bytes to the underlying resource.
107   *
108   * @param inputStream the input stream to be closed, or {@code null} in which case this method
109   *     does nothing
110   * @since 17.0
111   */
112  public static void closeQuietly(@Nullable InputStream inputStream) {
113    try {
114      close(inputStream, true);
115    } catch (IOException impossible) {
116      throw new AssertionError(impossible);
117    }
118  }
119
120  /**
121   * Closes the given {@link Reader}, logging any {@code IOException} that's thrown rather than
122   * propagating it.
123   *
124   * <p>While it's not safe in the general case to ignore exceptions that are thrown when closing an
125   * I/O resource, it should generally be safe in the case of a resource that's being used only for
126   * reading, such as a {@code Reader}. Unlike with writable resources, there's no chance that a
127   * failure that occurs when closing the reader indicates a meaningful problem such as a failure to
128   * flush all bytes to the underlying resource.
129   *
130   * @param reader the reader to be closed, or {@code null} in which case this method does nothing
131   * @since 17.0
132   */
133  public static void closeQuietly(@Nullable Reader reader) {
134    try {
135      close(reader, true);
136    } catch (IOException impossible) {
137      throw new AssertionError(impossible);
138    }
139  }
140}