title: Unable to decode a Base64 encoded object
body: <p>I am using salesforce api to get a salesforce document in my local machine. The document is base64 encoded. It is returned as an Object type. When I try to decode it to save it on my local machine, it gives an 'java.lang.ArrayIndexOutOfBoundsException: -84' error. I know it occurs when we try to access an non-existent index on an array but I am not doing that here. I am using commons library. </p>
  
  <p>Could anyone of you help me or suggest a better way to decode and store the file at my local machine.</p>
  
  <pre><code>import org.apache.commons.codec.binary.Base64; //and other imports
  private void querySample() {
      try {
          // Set query batch size
          partnerConnection.setQueryOptions(250);
  
          // SOQL query to use
          String soqlQuery = "SELECT Name, Body, BodyLength FROM Document LIMIT 1";
          // Make the query call and get the query results
          QueryResult qr = partnerConnection.query(soqlQuery);
  
          boolean done = false;
          SObject document;
          Object docName;
          Object docBody;
          Object bodyLength;
          byte[] encoded;
          byte[] decoded;
          int loopCount = 0;
          // Loop through the batches of returned results
          while (!done) {
              System.out.println("Records in results set " + loopCount++
                      + " - ");
              SObject[] records = qr.getRecords();
              // Process the query results
              for (int i = 0; i &lt; records.length; i++) {
                  document = records[i];
                  docName = document.getField("Name");
                  docBody = document.getField("Body");            //Body is base 64
                  bodyLength = document.getField("BodyLength");
  
                  encoded = serialize(docBody);
                  Integer size = Integer.parseInt((String) bodyLength);
  
                  decoded = new byte[size];   
  
                  decoded = Base64.decodeBase64(encoded); //&lt;-- Getting error here
  
                  String path = "D:\\myImage.png";
                  OutputStream out1 = new BufferedOutputStream(
                          new FileOutputStream(path));
                  out1.write(decoded);
  
              }
              if (qr.isDone()) {
                  done = true;
              } else {
                  qr =   partnerConnection.queryMore(qr.getQueryLocator());
              }
  
          }
      } catch (ConnectionException ce) {
          ce.printStackTrace();
      } catch (IOException ioe) {
          ioe.printStackTrace();
      }
      System.out.println("\nQuery execution completed.");
  
  }
  
  public static byte[] serialize(Object obj) throws IOException {
      ByteArrayOutputStream b = new ByteArrayOutputStream();
      ObjectOutputStream o = new ObjectOutputStream(b);
      o.writeObject(obj);
      return b.toByteArray();
  }
  </code></pre>