среда, 5 ноября 2008 г.

Reading from InputStream

Lately I've faced a simple problem: I needed to read all bytes from the InputStream. I didn't know type of the InputStream, so, I've spent more then two hours solving this problem without any success. I didn't want to read each byte from the stream. All evening I could think only about this problem. Solution turned to be very simple! I found a sample in the JDK installation directory($JAVA_HOME/sample/nio/). JDK 1.5(and higher) is a good API to work with streams over channels. The source code to read all bytes from the InputStream is rather simple:

  1. import java.io.IOException;  
  2. import java.io.InputStream;  
  3. import java.io.OutputStream;  
  4. import java.io.Reader;  
  5. import java.nio.ByteBuffer;  
  6. import java.nio.channels.Channels;  
  7. import java.nio.channels.ReadableByteChannel;  
  8.   
  9. /** 
  10.  * @author Pokidov.Dmitry 
  11.  *         Date: 13.04.2009 
  12.  */  
  13. public class IOHelper {  
  14.  /*Block size that we want to read in one time.*/  
  15.  private static final int READ_BLOCK = 8192;   
  16.   
  17.  /* 
  18.   * Read all from stream, using nio. 
  19.   * @param is source stream. 
  20.   * @return result byte array that read from source 
  21.   * @throws IOException by {@code Channel.read()} 
  22.   */  
  23.  public static byte[] readToEnd(InputStream is) throws IOException {  
  24.   //create channel for input stream  
  25.   ReadableByteChannel bc = Channels.newChannel(is);  
  26.   ByteBuffer bb = ByteBuffer.allocate(READ_BLOCK);  
  27.   
  28.   while (bc.read(bb) != -1) {  
  29.    bb = resizeBuffer(bb); //get new buffer for read  
  30.   }  
  31.   byte[] result = new byte[bb.position()];  
  32.   bb.position(0);  
  33.   bb.get(result);  
  34.   
  35.   return result;  
  36.  }  
  37.   
  38.  private static ByteBuffer resizeBuffer(ByteBuffer in) {  
  39.   ByteBuffer result = in;  
  40.   if (in.remaining() < READ_BLOCK) {  
  41.    //create new buffer  
  42.    result = ByteBuffer.allocate(in.capacity() * 2);  
  43.    //set limit to current position in buffer and set position to zero.  
  44.    in.flip();  
  45.    //put original buffer to new buffer  
  46.    result.put(in);  
  47.   }  
  48.   
  49.   return result;  
  50.  }  

Also I found an interesting book in which you can read about the nio package: get it here

Комментариев нет:

Most popular

Authors