使用 Java SDK API 从 Google 驱动器下载文件时出现内存不足错误

OutOfMemory Error in downloading file from Google Drive using Java SDK API

我正在使用google驱动JAVASDKAPI下载文件下面是代码,getGoogleDriveServiceInstance()方法将return下面代码中的驱动实例.此代码非常适合小文件,但对于大于 500 MB 的文件,我会遇到内存不足错误,我需要一些帮助来解决此问题。

public boolean downloadFile(String fileId, java.io.File path) {
         FileOutputStream fos=null;
         try{
             fos = new FileOutputStream(path);
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
             getGoogleDriveServiceInstance().files().get(fileId).executeMediaAndDownloadTo(baos);
             baos.writeTo(fos);
         } catch(Exception ex) {
             ex.printStackTrace();
             return false;
         } finally {
             try{fos.close();fos=null;} catch(Exception ex){}
         }
        return true;
    }

如果文件很大,会出现以下错误->

Exception in thread "Thread-22" java.lang.OutOfMemoryError: Java heap space
        at java.util.Arrays.copyOf(Arrays.java:2271)
        at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:113)
        at java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:93)
        at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:140)
        at com.google.api.client.util.ByteStreams.copy(ByteStreams.java:55)
        at com.google.api.client.util.IOUtils.copy(IOUtils.java:94)
        at com.google.api.client.util.IOUtils.copy(IOUtils.java:63)
        at com.google.api.client.googleapis.media.MediaHttpDownloader.executeCurrentRequest(MediaHttpDownloader.java:247)
        at com.google.api.client.googleapis.media.MediaHttpDownloader.download(MediaHttpDownloader.java:199)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeMediaAndDownloadTo(AbstractGoogleClientRequest.java:562)
        at com.google.api.services.drive.Drive$Files$Get.executeMediaAndDownloadTo(Drive.java:3560)

请参阅 https://developers.google.com/api-client-library/java/google-api-java-client/media-download,其中显示 "When you download a large media file from a server, use resumable media download to download the file chunk by chunk"。