1 /* 2 * Copyright (C) 2007 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.common.io; 18 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 2009.09.15 <b>tentative</b> 29 */ 30 public final class Flushables { 31 private static final Logger logger 32 = Logger.getLogger(Flushables.class.getName()); 33 34 private Flushables() {} 35 36 /** 37 * Flush a {@link Flushable}, with control over whether an 38 * {@code IOException} may be thrown. 39 * 40 * <p>If {@code swallowIOException} is true, then we don't rethrow 41 * {@code IOException}, but merely log it. 42 * 43 * @param flushable the {@code Flushable} object to be flushed. 44 * @param swallowIOException if true, don't propagate IO exceptions 45 * thrown by the {@code flush} method 46 * @throws IOException if {@code swallowIOException} is false and 47 * {@link Flushable#flush} throws an {@code IOException}. 48 * @see Closeables#close 49 */ 50 public static void flush(Flushable flushable, boolean swallowIOException) 51 throws IOException { 52 try { 53 flushable.flush(); 54 } catch (IOException e) { 55 logger.log(Level.WARNING, 56 "IOException thrown while flushing Flushable.", e); 57 if (!swallowIOException) { 58 throw e; 59 } 60 } 61 } 62 63 /** 64 * Equivalent to calling {@code flush(flushable, true)}, but with no 65 * {@code IOException} in the signature. 66 * 67 * @param flushable the {@code Flushable} object to be flushed. 68 */ 69 public static void flushQuietly(Flushable flushable) { 70 try { 71 flush(flushable, true); 72 } catch (IOException e) { 73 logger.log(Level.SEVERE, "IOException should not have been thrown.", e); 74 } 75 } 76 } 77