Search code examples
javaandroidgoogle-drive-android-api

Upload large files to the Google Drive


In my app, I'm uploading files to the google drive using GD API. It works fine for small file sizes, but when file size is large (ex: 200MB), it throws java.lang.OutOfMemoryError: exception. I know why it crashes it loads the whole data into the memory, can anyone suggest how can I fix this problem?

This is my code:

OutputStream outputStream = result.getDriveContents().getOutputStream();
FileInputStream fis;

try {
     fis = new FileInputStream(file.getPath());
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     byte[] buf = new byte[8192];
     int n;
     while (-1 != (n = fis.read(buf)))
            baos.write(buf, 0, n);
     byte[] photoBytes = baos.toByteArray();
     outputStream.write(photoBytes);

     outputStream.close();
     outputStream = null;
     fis.close();
     fis = null;
} catch (FileNotFoundException e) {                   
} 

Solution

  • This line would allocate 200 MB of RAM and can definitely cause OutOfMemoryError exception:

    byte[] photoBytes = baos.toByteArray();
    

    Why are you not writing directly to your outputStream:

    while (-1 != (n = fis.read(buf)))
            outputStream.write(buf, 0, n);