Hi,

On 11/28/06, Ted Roeloffzen <[EMAIL PROTECTED]> wrote:
> A common pattern I use when processing stream data is:
>
>    InputStream data = ...;
>    try {
>        byte[] buffer = new byte[BUFFER_SIZE];
>        for (int n = data.read(buffer); n != -1; n = data.read(buffer)) {
>            // process n bytes of data in buffer
>        }
>    } finally {
>        data.close();
>    }

When I do this, i need to know how large the buffer needs to be, but i don't
know how big it is. Is there a way to go around that?

The for loop is designed to read the stream in blocks. For example, you can use:

   private static final int BUFFER_SIZE = 1000;

... in which case the stream is read in blocks of up to a thousand
bytes. Each iteration of the for loop body will process a block of n
bytes stored in the allocated buffer.

For example if you want to store the image in a file or send it over
the network, you can do that by by writing the byte blocks to a
respective OutputStream, like this:

   InputStream data = ...;
   try {
       OutputStream destination = ...;
       try {
           byte[] buffer = new byte[BUFFER_SIZE];
           for (int n = data.read(buffer); n != -1; n = data.read(buffer)) {
               destination.write(buffer, 0, n);
           }
       } finally {
           destination.close();
       }
   } finally {
       data.close();
   }

If you need the whole binary stream available in memory as a byte
array, then you can use a ByteArrayOutputStream to accumulate the
data:

   OutputStream destination = new ByteArrayOutputStream();
   InputStream data = ...;
   try {
       byte[] buffer = new byte[BUFFER_SIZE];
       for (int n = data.read(buffer); n != -1; n = data.read(buffer)) {
           destination.write(buffer, 0, n);
       }
   } finally {
       data.close();
   }
   byte[] bytes = destination.toByteArray();

I hope this helps! See
http://java.sun.com/docs/books/tutorial/essential/io/bytestreams.html
and the related documentation for more information.

BR,

Jukka Zitting

Reply via email to