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