Copy the content of an input stream to an output stream

How to copy the content of an input stream to an output stream

/**
* Copy the content of the input stream into the output stream, using a temporary
* byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}.
*
* @param in The input stream to copy from.
* @param out The output stream to copy to.
*
* @throws IOException If any error occurs during the copy.
*/
private static final int IO_BUFFER_SIZE = 4 * 1024;

private static void copy(InputStream in, OutputStream out) throws IOException {
   byte[] b = new byte[IO_BUFFER_SIZE];
   int read;
   while ((read = in.read(b)) != -1) {
      out.write(b, 0, read);
   }
}
Share

Closing streams like a boss

This is one of my favorite tips and I also consider it a good practice.
How to close any java input or output Stream.

/**
* Closes the specified stream.
*
* @param stream The stream to close.
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
   try {
      stream.close();
   } catch (IOException e) {
   Log.e("IO", "Could not close stream", e);
}
} 
Share