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.util.logging.Level;
025import java.util.logging.Logger;
026
027import javax.annotation.Nullable;
028
029/**
030 * Utility methods for working with {@link Closeable} objects.
031 *
032 * @author Michael Lancaster
033 * @since 1.0
034 */
035@Beta
036public final class Closeables {
037  @VisibleForTesting static final Logger logger
038      = Logger.getLogger(Closeables.class.getName());
039
040  private Closeables() {}
041
042  /**
043   * Closes a {@link Closeable}, with control over whether an {@code IOException} may be thrown.
044   * This is primarily useful in a finally block, where a thrown exception needs to be logged but
045   * not propagated (otherwise the original exception will be lost).
046   *
047   * <p>If {@code swallowIOException} is true then we never throw {@code IOException} but merely log
048   * it.
049   *
050   * <p>Example: <pre>   {@code
051   *
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   *   }}</pre>
063   *
064   * @param closeable the {@code Closeable} object to be closed, or null, in which case this method
065   *     does nothing
066   * @param swallowIOException if true, don't propagate IO exceptions thrown by the {@code close}
067   *     methods
068   * @throws IOException if {@code swallowIOException} is false and {@code close} throws an
069   *     {@code IOException}.
070   */
071  public static void close(@Nullable Closeable closeable,
072      boolean swallowIOException) throws IOException {
073    if (closeable == null) {
074      return;
075    }
076    try {
077      closeable.close();
078    } catch (IOException e) {
079      if (swallowIOException) {
080        logger.log(Level.WARNING,
081            "IOException thrown while closing Closeable.", e);
082      } else {
083        throw e;
084      }
085    }
086  }
087
088  /**
089   * Equivalent to calling {@code close(closeable, true)}, but with no IOException in the signature.
090   *
091   * @param closeable the {@code Closeable} object to be closed, or null, in which case this method
092   *     does nothing
093   * @deprecated Where possible, use the
094   *     <a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html">
095   *     try-with-resources</a> statement if using JDK7 or {@link Closer} on JDK6 to close one or
096   *     more {@code Closeable} objects. This method is deprecated because it is easy to misuse and
097   *     may swallow IO exceptions that really should be thrown and handled. See
098   *     <a href="https://code.google.com/p/guava-libraries/issues/detail?id=1118">Guava issue
099   *     1118</a> for a more detailed explanation of the reasons for deprecation and see
100   *     <a href="https://code.google.com/p/guava-libraries/wiki/ClosingResourcesExplained">
101   *     Closing Resources</a> for more information on the problems with closing {@code Closeable}
102   *     objects and some of the preferred solutions for handling it correctly. This method is
103   *     scheduled to be removed in Guava 16.0.
104   */
105  @Deprecated
106  public static void closeQuietly(@Nullable Closeable closeable) {
107    try {
108      close(closeable, true);
109    } catch (IOException e) {
110      logger.log(Level.SEVERE, "IOException should not have been thrown.", e);
111    }
112  }
113}