将大文件上传到 Google 驱动器

Upload large files to the Google Drive

在我的应用程序中,我使用 GD API 将文件上传到 google 驱动器。它适用于小文件大小,但当文件大小很大(例如:200MB)时,它会抛出 java.lang.OutOfMemoryError: 异常。我知道为什么它会崩溃它将整个数据加载到内存中,有人可以建议我如何解决这个问题吗?

这是我的代码:

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) {                   
} 

此行将分配 200 MB 的 RAM,并且肯定会导致 OutOfMemoryError 异常:

byte[] photoBytes = baos.toByteArray();

你为什么不直接写信给你的 outputStream:

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