/*************************************** * * * JBoss: The OpenSource J2EE WebOS * * * * Distributable under LGPL license. * * See terms of license at gnu.org. * * * ***************************************/ package org.jboss.util.stream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import org.jboss.util.ThrowableHandler; import org.jboss.logging.Logger; /** * A collection of stream related utility methods. * *
Exceptions that are thrown and not explicitly declared are given to
* the {@link ThrowableHandler} for further processing.
*
* @version $Revision: 1.4 $
* @author Jason Dillon
*/
public final class Streams
{
private static final Logger log = Logger.getLogger(Streams.class);
/////////////////////////////////////////////////////////////////////////
// Closing //
/////////////////////////////////////////////////////////////////////////
/**
* Attempt to close an InputStream.
*
* @param stream InputStream to attempt to close.
* @return True if stream was closed (or stream was null),
* or false if an exception was thrown.
*/
public static boolean close(final InputStream stream) {
// do not attempt to close null stream, but return sucess
if (stream == null) {
return true;
}
boolean success = true;
try {
stream.close();
}
catch (IOException e) {
success = false;
ThrowableHandler.add(e);
}
return success;
}
/**
* Attempt to close an OutputStream.
*
* @param stream OutputStream to attempt to close.
* @return True if stream was closed (or stream was null),
* or false if an exception was thrown.
*/
public static boolean close(final OutputStream stream) {
// do not attempt to close null stream, but return sucess
if (stream == null) {
return true;
}
boolean success = true;
try {
stream.close();
}
catch (IOException e) {
success = false;
ThrowableHandler.add(e);
}
return success;
}
/**
* Attempt to close an InputStream or OutputStream.
*
* @param stream Stream to attempt to close.
* @return True if stream was closed (or stream was null),
* or false if an exception was thrown.
*
* @throws IllegalArgumentException Stream is not an InputStream
* or OuputStream.
*/
public static boolean close(final Object stream) {
boolean success = false;
if (stream instanceof InputStream) {
success = close((InputStream)stream);
}
else if (stream instanceof OutputStream) {
success = close((OutputStream)stream);
}
else {
throw new IllegalArgumentException
("stream is not an InputStream or OutputStream");
}
return success;
}
/**
* Attempt to close an array of InputStreams.
*
* @param streams Array of InputStreams to attempt to close.
* @return True if all streams were closed, or false
* if an exception was thrown.
*/
public static boolean close(final InputStream[] streams) {
boolean success = true;
for (int i=0; i