title: How to read bytes into arrays by specifying offset and byte length using the DataInputStream class?
body: <p>I declare and allocate some byte arrays. I want to initialize these arrays with the read(byte array, offset, byte length) method. The first read method statement seems to read the first 32 bytes correctly into the array. However, the second read method does not and throws an indexOutOfBounds exception.</p>
  
  <p>Specification for the offset values:</p>
  
  <pre><code>offset 0, length 32 bytes - contains some text
  offset 32, length 2 bytes - contains something else
  etc
  </code></pre>
  
  <p>Here is the code:</p>
  
  <pre><code>File file = new File("somebinaryfile.dat");
  DataInputStream in = new DataInputStream(new FileInputStream(file));
  
  byte[] array1 = new byte[32];   // first array 
  byte[] array2 = new byte[2];    // second array
  
  in.read(array1, 0, 32);
  in.read(array2, 32, 2);
  
  in.close();
  </code></pre>
  
  <p>I'm working under the assumption(probably incorrectly) that the read position will automatically increase during each new .read() method statement. Yet if I allocate 34 elements to array2 instead of just 2 elements, then no exception is thrown. Therefore, it appears that the first 34 bytes are being read into array2 instead of just the last 2 bytes even though I'm specifying offset and byte length...</p>
  
  <p>I realize the RandomAccessFile class has a nifty .seek(n) method. However, I'm pretty stubborn and want to stick with DataInputStream.</p>
  
  <p>Any advice on correct usage in order to initialize the two arrays with data obtained using the specified offset and byte length?</p>