title: Best practice to read limited length from an input stream
body: <p>I have packets that are sent over sockets which are preceded by length headers. So every transmission comes with 4 bytes of length information followed by the packet. Therefore, I must limit my <code>read()</code> to never exceed the length, so that I don't accidentally read the next packet in line.</p>
  
  <p><code>InputStream in</code> is the input stream, <code>ByteArrayOutputStream byteStream</code> is the stream I write incoming packets into and <code>int len</code> is the length of an incoming transmission.</p>
  
  <p>Here is what I came up with:</p>
  
  <pre><code>for (int i = 0; i &lt; len; i++) {
      byteStream.write(in.read());
  }
  </code></pre>
  
  <p>This is absolutely horrific; reading bytes one by one. I was hoping to see if there is a better way of doing this using buffers (kind of similar to the canonical way of copying streams).</p>