View Javadoc
1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  
15  package com.google.common.io;
16  
17  import com.google.common.annotations.Beta;
18  import com.google.common.annotations.GwtIncompatible;
19  import com.google.common.annotations.VisibleForTesting;
20  import java.io.Closeable;
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.io.Reader;
24  import java.util.logging.Level;
25  import java.util.logging.Logger;
26  import javax.annotation.Nullable;
27  
28  /**
29   * Utility methods for working with {@link Closeable} objects.
30   *
31   * @author Michael Lancaster
32   * @since 1.0
33   */
34  @Beta
35  @GwtIncompatible
36  public final class Closeables {
37    @VisibleForTesting static final Logger logger = Logger.getLogger(Closeables.class.getName());
38  
39    private Closeables() {}
40  
41    /**
42     * Closes a {@link Closeable}, with control over whether an {@code IOException} may be thrown.
43     * This is primarily useful in a finally block, where a thrown exception needs to be logged but
44     * not propagated (otherwise the original exception will be lost).
45     *
46     * <p>If {@code swallowIOException} is true then we never throw {@code IOException} but merely log
47     * it.
48     *
49     * <p>Example: <pre>   {@code
50     *
51     *   public void useStreamNicely() throws IOException {
52     *     SomeStream stream = new SomeStream("foo");
53     *     boolean threw = true;
54     *     try {
55     *       // ... code which does something with the stream ...
56     *       threw = false;
57     *     } finally {
58     *       // If an exception occurs, rethrow it only if threw==false:
59     *       Closeables.close(stream, threw);
60     *     }
61     *   }}</pre>
62     *
63     * @param closeable the {@code Closeable} object to be closed, or null, in which case this method
64     *     does nothing
65     * @param swallowIOException if true, don't propagate IO exceptions thrown by the {@code close}
66     *     methods
67     * @throws IOException if {@code swallowIOException} is false and {@code close} throws an
68     *     {@code IOException}.
69     */
70    public static void close(@Nullable Closeable closeable, boolean swallowIOException)
71        throws IOException {
72      if (closeable == null) {
73        return;
74      }
75      try {
76        closeable.close();
77      } catch (IOException e) {
78        if (swallowIOException) {
79          logger.log(Level.WARNING, "IOException thrown while closing Closeable.", e);
80        } else {
81          throw e;
82        }
83      }
84    }
85  
86    /**
87     * Closes the given {@link InputStream}, logging any {@code IOException} that's thrown rather than
88     * propagating it.
89     *
90     * <p>While it's not safe in the general case to ignore exceptions that are thrown when closing an
91     * I/O resource, it should generally be safe in the case of a resource that's being used only for
92     * reading, such as an {@code InputStream}. Unlike with writable resources, there's no chance that
93     * a failure that occurs when closing the stream indicates a meaningful problem such as a failure
94     * to flush all bytes to the underlying resource.
95     *
96     * @param inputStream the input stream to be closed, or {@code null} in which case this method
97     *     does nothing
98     * @since 17.0
99     */
100   public static void closeQuietly(@Nullable InputStream inputStream) {
101     try {
102       close(inputStream, true);
103     } catch (IOException impossible) {
104       throw new AssertionError(impossible);
105     }
106   }
107 
108   /**
109    * Closes the given {@link Reader}, logging any {@code IOException} that's thrown rather than
110    * propagating it.
111    *
112    * <p>While it's not safe in the general case to ignore exceptions that are thrown when closing an
113    * I/O resource, it should generally be safe in the case of a resource that's being used only for
114    * reading, such as a {@code Reader}. Unlike with writable resources, there's no chance that a
115    * failure that occurs when closing the reader indicates a meaningful problem such as a failure to
116    * flush all bytes to the underlying resource.
117    *
118    * @param reader the reader to be closed, or {@code null} in which case this method does nothing
119    * @since 17.0
120    */
121   public static void closeQuietly(@Nullable Reader reader) {
122     try {
123       close(reader, true);
124     } catch (IOException impossible) {
125       throw new AssertionError(impossible);
126     }
127   }
128 }