@Beta public final class Closeables extends Object
Closeable
objects.Modifier and Type | Method and Description |
---|---|
static void |
close(Closeable closeable,
boolean swallowIOException)
Closes a
Closeable , with control over whether an IOException may be thrown. |
static void |
closeQuietly(Closeable closeable)
Deprecated.
Where possible, use the
try-with-resources statement if using JDK7 or
Closer on JDK6 to close one or
more Closeable objects. This method is deprecated because it is easy to misuse and
may swallow IO exceptions that really should be thrown and handled. See
Guava issue
1118 for a more detailed explanation of the reasons for deprecation and see
Closing Resources for more information on the problems with closing Closeable
objects and some of the preferred solutions for handling it correctly. This method is
scheduled to be removed in Guava 16.0. |
public static void close(@Nullable Closeable closeable, boolean swallowIOException) throws IOException
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).
If swallowIOException
is true then we never throw IOException
but merely log
it.
Example:
public void useStreamNicely() throws IOException {
SomeStream stream = new SomeStream("foo");
boolean threw = true;
try {
// ... code which does something with the stream ...
threw = false;
} finally {
// If an exception occurs, rethrow it only if threw==false:
Closeables.close(stream, threw);
}
}
closeable
- the Closeable
object to be closed, or null, in which case this method
does nothingswallowIOException
- if true, don't propagate IO exceptions thrown by the close
methodsIOException
- if swallowIOException
is false and close
throws an
IOException
.@Deprecated public static void closeQuietly(@Nullable Closeable closeable)
Closer
on JDK6 to close one or
more Closeable
objects. This method is deprecated because it is easy to misuse and
may swallow IO exceptions that really should be thrown and handled. See
Guava issue
1118 for a more detailed explanation of the reasons for deprecation and see
Closing Resources for more information on the problems with closing Closeable
objects and some of the preferred solutions for handling it correctly. This method is
scheduled to be removed in Guava 16.0.close(closeable, true)
, but with no IOException in the signature.closeable
- the Closeable
object to be closed, or null, in which case this method
does nothingCopyright © 2010-2013. All Rights Reserved.