[ Back | Previous | Next ]

How to send binary data over a stream with OutputStream?

Package:
java.io.*
Product:
JDK
Release:
1.0.2
Related Links:
General
File
FilenameFilter
FileWriter
JPEGCodec
ObjectInputStream
OutputStream
PipedInputStream
PrintWriter
StreamTokenizer
Comment:

For me it is sometimes hard to choose which way is fast or best to send a certain amount of data over a stream. To make this desicion easier I made this sample with the BufferedOutputStream.

What happens is that the out OutputStream is filled with the data from the RandomAccessFile (or any other InputStream). The while loop fills the loader buffer and writes it to the outputstream. This it the first aspect. The second aspect is to flush the outputstream and properly close it. After this you've transfered the data from the input to the output.

Here's the example:

        try {
          
          dot_clearImage = new File( "images.gif" );

          // if not exists abort
          if ( dot_clearImage.exists() ) {
            res.setContentType("image/gif");
            RandomAccessFile raf = new RandomAccessFile( dot_clearImage, "r" );
            out = res.getOutputStream();
            
            byte [] loader = new byte [ (int) raf.length() ];
            while ( (raf.read( loader )) > 0 ) {
              out.write( loader );
            }
          } 
          
        } catch (IOException ioe) {
          System.out.println("Unable to open Image file "); ioe.printStackTrace();
        } finally {
          if (out != null) {
            out.flush();
            out.close();
          }
        }


1