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 032public final class Flushables { 033 private static final Logger logger = Logger.getLogger(Flushables.class.getName()); 034 035 private Flushables() {} 036 037 /** 038 * Flush a {@link Flushable}, with control over whether an {@code IOException} may be thrown. 039 * 040 * <p>If {@code swallowIOException} is true, then we don't rethrow {@code IOException}, but merely 041 * log it. 042 * 043 * @param flushable the {@code Flushable} object to be flushed. 044 * @param swallowIOException if true, don't propagate IO exceptions thrown by the {@code flush} 045 * method 046 * @throws IOException if {@code swallowIOException} is false and {@link Flushable#flush} throws 047 * an {@code IOException}. 048 * @see Closeables#close 049 */ 050 public static void flush(Flushable flushable, boolean swallowIOException) throws IOException { 051 try { 052 flushable.flush(); 053 } catch (IOException e) { 054 if (swallowIOException) { 055 logger.log(Level.WARNING, "IOException thrown while flushing Flushable.", e); 056 } else { 057 throw e; 058 } 059 } 060 } 061 062 /** 063 * Equivalent to calling {@code flush(flushable, true)}, but with no {@code IOException} in the 064 * signature. 065 * 066 * @param flushable the {@code Flushable} object to be flushed. 067 */ 068 public static void flushQuietly(Flushable flushable) { 069 try { 070 flush(flushable, true); 071 } catch (IOException e) { 072 logger.log(Level.SEVERE, "IOException should not have been thrown.", e); 073 } 074 } 075}