title: Android:"Unexpected end of stream" exception downloading large files
body: <p>I am building an Android Application and I need to download a file from a url, which is 33 MB large.</p>
  
  <p>Here the download task:</p>
  
  <pre><code>try {
              int MAX_BUFFER_SIZE = 4096;
              URL mUrl = new URL(params[0]);
              HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();
              connection.setRequestMethod("GET");
              long length = connection.getContentLength(), downloaded = 0;
              int read;
              byte [] buffer = new byte[(((int)length) &gt; MAX_BUFFER_SIZE) ? MAX_BUFFER_SIZE : (int)length];
              String filename = getFilename(mUrl);
              File file = new File (SDCARD_ROOT);
              if (!file.exists() || !file.isDirectory()){
                  file.mkdir();
              }
              this.filename = filename;
              file = new File (SDCARD_ROOT + this.filename);  
              FileOutputStream fos = new FileOutputStream (file);
              //Start downloading
              InputStream stream = connection.getInputStream();
  
              while ((read=stream.read(buffer)) &gt; -1){
                  fos.write(buffer, 0, read);
                  downloaded += read;
                  publishProgress((int) ((float) downloaded/length * 100));
              }
              fos.close();
              return 1;
          } catch (Exception e){
              Log.e("REV-PARTS", "Revolver parts error in DownloadTask: " + e.getMessage());  
              return 2;
          }
  </code></pre>
  
  <p>It works right with small files (1-15 MB), but it will return a "unexpected end of stream" exception with large files.</p>