com.google.gdata.util.common.io
Class Closeables

java.lang.Object
  extended by com.google.gdata.util.common.io.Closeables

public final class Closeables
extends java.lang.Object

Utility methods for working with Closeable objects.


Method Summary
static void close(java.io.Closeable closeable, boolean swallowIOException)
          Close a Closeable, with control over whether an IOException may be thrown.
static void closeQuietly(java.io.Closeable closeable)
          Equivalent to calling close(closeable, true), but with no IOException in the signature.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

close

public static void close(java.io.Closeable closeable,
                         boolean swallowIOException)
                  throws java.io.IOException
Close a Closeable, with control over whether an IOException may be thrown. This is primarily useful in a finally block, where a thrown exception needs to be logged but not propagated (otherwise the original exception will be lost). The Closeable object is also checked to see if it implements Flushable and if it does, it is flushed before closing.

If flush throws an exception, we try to close the Closeable before continuing. If close also throws an exception and swallowIOException is false, then we rethrow close exception, otherwise we rethrow the flush exception.

If swallowIOException is true then we never throw IOException but merely log it.

Example:

public void useStreamNicely() throws OtherException {
 boolean threw = true;
 SomeStream stream = null;
 try {
   stream = new SomeStream("foo");
   // Some code which does something with the Stream. May throw a
   // Throwable.
   threw = false; // No throwable thrown.
 } catch (SomeException e) {
   throw new OtherException(e);
 } finally {
   // Close (and flush if Flushable) the stream.
   // If an exception occurs, only rethrow it if (threw==false).
   Closeables.close(stream, threw);
 }
 

Parameters:
closeable - the Closeable object to be closed, or null, in which case this method does nothing
swallowIOException - if true, don't propagate IO exceptions thrown by the close or flush methods
Throws:
java.io.IOException - if swallowIOException is false and close or flush throws an IOException.

closeQuietly

public static void closeQuietly(java.io.Closeable closeable)
Equivalent to calling close(closeable, true), but with no IOException in the signature.

Parameters:
closeable - the Closeable object to be closed, or null, in which case this method does nothing