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.J2ktIncompatible;
020import com.google.common.annotations.VisibleForTesting;
021import java.io.Closeable;
022import java.io.IOException;
023import java.io.InputStream;
024import java.io.Reader;
025import java.util.logging.Level;
026import java.util.logging.Logger;
027import javax.annotation.CheckForNull;
028
029/**
030 * Utility methods for working with {@link Closeable} objects.
031 *
032 * @author Michael Lancaster
033 * @since 1.0
034 */
035@Beta
036@J2ktIncompatible
037@GwtIncompatible
038@ElementTypesAreNonnullByDefault
039public final class Closeables {
040  @VisibleForTesting static final Logger logger = Logger.getLogger(Closeables.class.getName());
041
042  private Closeables() {}
043
044  /**
045   * Closes a {@link Closeable}, with control over whether an {@code IOException} may be thrown.
046   * This is primarily useful in a finally block, where a thrown exception needs to be logged but
047   * not propagated (otherwise the original exception will be lost).
048   *
049   * <p>If {@code swallowIOException} is true then we never throw {@code IOException} but merely log
050   * it.
051   *
052   * <p>Example:
053   *
054   * <pre>{@code
055   * public void useStreamNicely() throws IOException {
056   *   SomeStream stream = new SomeStream("foo");
057   *   boolean threw = true;
058   *   try {
059   *     // ... code which does something with the stream ...
060   *     threw = false;
061   *   } finally {
062   *     // If an exception occurs, rethrow it only if threw==false:
063   *     Closeables.close(stream, threw);
064   *   }
065   * }
066   * }</pre>
067   *
068   * @param closeable the {@code Closeable} object to be closed, or null, in which case this method
069   *     does nothing
070   * @param swallowIOException if true, don't propagate IO exceptions thrown by the {@code close}
071   *     methods
072   * @throws IOException if {@code swallowIOException} is false and {@code close} throws an {@code
073   *     IOException}.
074   */
075  public static void close(@CheckForNull Closeable closeable, boolean swallowIOException)
076      throws IOException {
077    if (closeable == null) {
078      return;
079    }
080    try {
081      closeable.close();
082    } catch (IOException e) {
083      if (swallowIOException) {
084        logger.log(Level.WARNING, "IOException thrown while closing Closeable.", e);
085      } else {
086        throw e;
087      }
088    }
089  }
090
091  /**
092   * Closes the given {@link InputStream}, logging any {@code IOException} that's thrown rather than
093   * propagating it.
094   *
095   * <p>While it's not safe in the general case to ignore exceptions that are thrown when closing an
096   * I/O resource, it should generally be safe in the case of a resource that's being used only for
097   * reading, such as an {@code InputStream}. Unlike with writable resources, there's no chance that
098   * a failure that occurs when closing the stream indicates a meaningful problem such as a failure
099   * to flush all bytes to the underlying resource.
100   *
101   * @param inputStream the input stream to be closed, or {@code null} in which case this method
102   *     does nothing
103   * @since 17.0
104   */
105  public static void closeQuietly(@CheckForNull InputStream inputStream) {
106    try {
107      close(inputStream, true);
108    } catch (IOException impossible) {
109      throw new AssertionError(impossible);
110    }
111  }
112
113  /**
114   * Closes the given {@link Reader}, logging any {@code IOException} that's thrown rather than
115   * propagating it.
116   *
117   * <p>While it's not safe in the general case to ignore exceptions that are thrown when closing an
118   * I/O resource, it should generally be safe in the case of a resource that's being used only for
119   * reading, such as a {@code Reader}. Unlike with writable resources, there's no chance that a
120   * failure that occurs when closing the reader indicates a meaningful problem such as a failure to
121   * flush all bytes to the underlying resource.
122   *
123   * @param reader the reader to be closed, or {@code null} in which case this method does nothing
124   * @since 17.0
125   */
126  public static void closeQuietly(@CheckForNull Reader reader) {
127    try {
128      close(reader, true);
129    } catch (IOException impossible) {
130      throw new AssertionError(impossible);
131    }
132  }
133}