title: Android File To Base64 using streaming sometimes missed 2 bytes
body: <p>i am writing to ask for the proper solution for solving the following difficulties:</p>
  
  <p>I am required to encode the file in Base64 format, and there is no way for me to make the file small, as a result, i will surely suffered from OutOfMemory Exception, that why i used Streaming approach for solving it. 
  After the file is encoded, i have decoded it immediately by code and also online-tools. The decoded content was found missing 2 bytes at the end of the file sometimes, but not always. It did affected further processing to the file.</p>
  
  <p>Hope someone could help and may be caused by an idiot mistake. Still thanks.</p>
  
  <p>Here is the Code:</p>
  
  <pre><code>FileOutputStream fout = new FileOutputStream(path + ".txt");
  //this is for printing out the base64 content
  FileInputStream fin = new FileInputStream(path);
  
  System.out.println("File Size:" + path.getTotalSpace());
  
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  Base64OutputStream base64out = new Base64OutputStream(os,Base64.NO_WRAP);
  
  byte[] buffer = new byte[3 * 512];
  int len = 0;
  while ((len = fin.read(buffer)) &gt;= 0) {
      base64out.write(buffer, 0, len);
  }
  
  System.out.println("Encoded Size:" + os.size());
  
  String result = new String(os.toByteArray(), "UTF-8");
  
  fout.write(os.toByteArray());
  fout.close();
  base64out.close();
  os.close();
  fin.close();
  
  return result;
  </code></pre>