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