001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.io;
016
017import com.google.common.annotations.Beta;
018import com.google.common.annotations.GwtIncompatible;
019import java.io.Flushable;
020import java.io.IOException;
021import java.util.logging.Level;
022import java.util.logging.Logger;
023
024/**
025 * Utility methods for working with {@link Flushable} objects.
026 *
027 * @author Michael Lancaster
028 * @since 1.0
029 */
030@Beta
031@GwtIncompatible
032@ElementTypesAreNonnullByDefault
033public final class Flushables {
034  private static final Logger logger = Logger.getLogger(Flushables.class.getName());
035
036  private Flushables() {}
037
038  /**
039   * Flush a {@link Flushable}, with control over whether an {@code IOException} may be thrown.
040   *
041   * <p>If {@code swallowIOException} is true, then we don't rethrow {@code IOException}, but merely
042   * log it.
043   *
044   * @param flushable the {@code Flushable} object to be flushed.
045   * @param swallowIOException if true, don't propagate IO exceptions thrown by the {@code flush}
046   *     method
047   * @throws IOException if {@code swallowIOException} is false and {@link Flushable#flush} throws
048   *     an {@code IOException}.
049   * @see Closeables#close
050   */
051  public static void flush(Flushable flushable, boolean swallowIOException) throws IOException {
052    try {
053      flushable.flush();
054    } catch (IOException e) {
055      if (swallowIOException) {
056        logger.log(Level.WARNING, "IOException thrown while flushing Flushable.", e);
057      } else {
058        throw e;
059      }
060    }
061  }
062
063  /**
064   * Equivalent to calling {@code flush(flushable, true)}, but with no {@code IOException} in the
065   * signature.
066   *
067   * @param flushable the {@code Flushable} object to be flushed.
068   */
069  public static void flushQuietly(Flushable flushable) {
070    try {
071      flush(flushable, true);
072    } catch (IOException e) {
073      logger.log(Level.SEVERE, "IOException should not have been thrown.", e);
074    }
075  }
076}