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 java.io.Flushable;
20  import java.io.IOException;
21  import java.util.logging.Level;
22  import java.util.logging.Logger;
23  
24  /**
25   * Utility methods for working with {@link Flushable} objects.
26   *
27   * @author Michael Lancaster
28   * @since 1.0
29   */
30  @Beta
31  @GwtIncompatible
32  public final class Flushables {
33    private static final Logger logger = Logger.getLogger(Flushables.class.getName());
34  
35    private Flushables() {}
36  
37    /**
38     * Flush a {@link Flushable}, with control over whether an {@code IOException} may be thrown.
39     *
40     * <p>If {@code swallowIOException} is true, then we don't rethrow {@code IOException}, but merely
41     * log it.
42     *
43     * @param flushable the {@code Flushable} object to be flushed.
44     * @param swallowIOException if true, don't propagate IO exceptions thrown by the {@code flush}
45     *     method
46     * @throws IOException if {@code swallowIOException} is false and {@link Flushable#flush} throws
47     *     an {@code IOException}.
48     * @see Closeables#close
49     */
50    public static void flush(Flushable flushable, boolean swallowIOException) throws IOException {
51      try {
52        flushable.flush();
53      } catch (IOException e) {
54        if (swallowIOException) {
55          logger.log(Level.WARNING, "IOException thrown while flushing Flushable.", e);
56        } else {
57          throw e;
58        }
59      }
60    }
61  
62    /**
63     * Equivalent to calling {@code flush(flushable, true)}, but with no {@code IOException} in the
64     * signature.
65     *
66     * @param flushable the {@code Flushable} object to be flushed.
67     */
68    public static void flushQuietly(Flushable flushable) {
69      try {
70        flush(flushable, true);
71      } catch (IOException e) {
72        logger.log(Level.SEVERE, "IOException should not have been thrown.", e);
73      }
74    }
75  }