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    
017    package com.google.common.io;
018    
019    import com.google.common.annotations.Beta;
020    
021    import java.io.Flushable;
022    import java.io.IOException;
023    import java.util.logging.Level;
024    import java.util.logging.Logger;
025    
026    /**
027     * Utility methods for working with {@link Flushable} objects.
028     *
029     * @author Michael Lancaster
030     * @since 1
031     */
032    @Beta
033    public final class Flushables {
034      private static final Logger logger
035          = Logger.getLogger(Flushables.class.getName());
036    
037      private Flushables() {}
038    
039      /**
040       * Flush a {@link Flushable}, with control over whether an
041       * {@code IOException} may be thrown.
042       *
043       * <p>If {@code swallowIOException} is true, then we don't rethrow
044       * {@code IOException}, but merely log it.
045       *
046       * @param flushable the {@code Flushable} object to be flushed.
047       * @param swallowIOException if true, don't propagate IO exceptions
048       *     thrown by the {@code flush} method
049       * @throws IOException if {@code swallowIOException} is false and
050       *     {@link Flushable#flush} throws an {@code IOException}.
051       * @see Closeables#close
052       */
053      public static void flush(Flushable flushable, boolean swallowIOException)
054          throws IOException {
055        try {
056          flushable.flush();
057        } catch (IOException e) {
058          if (swallowIOException) {
059            logger.log(Level.WARNING,
060                "IOException thrown while flushing Flushable.", e);
061          } else {
062            throw e;
063          }
064        }
065      }
066    
067      /**
068       * Equivalent to calling {@code flush(flushable, true)}, but with no
069       * {@code IOException} in the signature.
070       *
071       * @param flushable the {@code Flushable} object to be flushed.
072       */
073      public static void flushQuietly(Flushable flushable) {
074        try {
075          flush(flushable, true);
076        } catch (IOException e) {
077          logger.log(Level.SEVERE, "IOException should not have been thrown.", e);
078        }
079      }
080    }