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 017package com.google.common.io; 018 019import com.google.common.annotations.Beta; 020import com.google.common.annotations.VisibleForTesting; 021 022import java.io.Closeable; 023import java.io.IOException; 024import java.util.logging.Level; 025import java.util.logging.Logger; 026 027import javax.annotation.Nullable; 028 029/** 030 * Utility methods for working with {@link Closeable} objects. 031 * 032 * @author Michael Lancaster 033 * @since 1.0 034 */ 035@Beta 036public final class Closeables { 037 @VisibleForTesting static final Logger logger 038 = Logger.getLogger(Closeables.class.getName()); 039 040 private Closeables() {} 041 042 /** 043 * Closes a {@link Closeable}, with control over whether an {@code IOException} may be thrown. 044 * This is primarily useful in a finally block, where a thrown exception needs to be logged but 045 * not propagated (otherwise the original exception will be lost). 046 * 047 * <p>If {@code swallowIOException} is true then we never throw {@code IOException} but merely log 048 * it. 049 * 050 * <p>Example: <pre> {@code 051 * 052 * public void useStreamNicely() throws IOException { 053 * SomeStream stream = new SomeStream("foo"); 054 * boolean threw = true; 055 * try { 056 * // ... code which does something with the stream ... 057 * threw = false; 058 * } finally { 059 * // If an exception occurs, rethrow it only if threw==false: 060 * Closeables.close(stream, threw); 061 * } 062 * }}</pre> 063 * 064 * @param closeable the {@code Closeable} object to be closed, or null, in which case this method 065 * does nothing 066 * @param swallowIOException if true, don't propagate IO exceptions thrown by the {@code close} 067 * methods 068 * @throws IOException if {@code swallowIOException} is false and {@code close} throws an 069 * {@code IOException}. 070 */ 071 public static void close(@Nullable Closeable closeable, 072 boolean swallowIOException) throws IOException { 073 if (closeable == null) { 074 return; 075 } 076 try { 077 closeable.close(); 078 } catch (IOException e) { 079 if (swallowIOException) { 080 logger.log(Level.WARNING, 081 "IOException thrown while closing Closeable.", e); 082 } else { 083 throw e; 084 } 085 } 086 } 087}