Home | FAQ | Contact me

Slurping a stream...

This is some code I wrote to slurp bytes out of an InputStream such as might come back via request.getInputStream(). I show this as a private, helper method inside another class since that's how I used it.

Inside this code

In terms of beginning Java samples you have:

  • Use of classes StringBuffer and String.
  • Use of byte as an intermediary.
  • Use of common method toString().

Eclipse tip: Call Hierarchy

Double-click in the editor to highlight a method, then hold down the Crtl and Alt buttons while typing an 'h' to see, in the Call Hierarchy pane, other methods that call this one.

Note that some stream handlers don't require such intermediary. For example:

import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.JDomDriver; ... void someMethod( InputStream is ) { XStream xs - new XStream( new JDomDriver() ); ... xs.alias( method, whichClass ); String string = ( String ) xs.fromXML( is ); ... }
package com.etretatlogiciels.samples.streams;

import java.io.InputStream;
import java.lang.StringBuffer;
import java.io.IOException;

public class SomeClass
{
  .
  .
  .

  /**
   * This sips at a stream turning the whole thing into a String.
   *
   * @param in - the in-coming stream (InputStream)
   * @return a new string with the contents of the input stream (String)
   * @throws IOException
   */
  private static String slurp( InputStream in ) throws IOException
  {
    int          n   = 0;
    StringBuffer out = new StringBuffer();
    byte[]       b   = new byte[ 4096 ];

    while( ( n = in.read( b ) ) != -1 )
        out.append( new String( b, 0, n ) );

    return out.toString();
  }

  .
  .
  .
}
// vim: set tabstop=2 shiftwidth=2 noexpandtab: