title: Java: How to "trim" a byte array?
body: <p>So I have some code that reads a certain amount of bytes from a file and returns the resulting byte array (this is basically used for chunking up files to send over the network as (eventually) base64-encoded ascii text).</p>
  
  <p>It works fine, except that when the last chunk of the file is generated, it isnt a full chunk. Therefore, the resulting byte array isnt full. However, it is a constant size, which means that the file is reassembled there is a whole bunch of extra data (0's maybe) appended to the end.</p>
  
  <p>How can I make it so that the byte[] for the last chunk of the file really only contains the data it needs to? The code looks like this:</p>
  
  <pre><code> private byte[] readData(File f, int startByte, int chunkSize) throws Exception {
      RandomAccessFile raf = new RandomAccessFile(f, "r");
      raf.seek(startByte);
      byte[] data = new byte[chunkSize];
      raf.read(data);        
      raf.close();
      return data;
  }
  </code></pre>
  
  <p>So if chunkSize is bigger than the remaining bytes in the file, a full sized byte[] gets returned but its only half-full with data.</p>