【问题标题】:OutOfMemory Error in downloading file from Google Drive using Java SDK API使用 Java SDK API 从 Google Drive 下载文件时出现 OutOfMemory 错误
【发布时间】:2017-01-19 06:55:00
【问题描述】:

我正在使用google drive JAVA SDK API下载文件下面是代码,getGoogleDriveServiceInstance()方法将在下面的代码中返回Drive实例。此代码非常适合小文件,但对于 > 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)

【问题讨论】:

  • 提示:你有没有想过...为什么我们需要从流开始?为什么不将整个文件作为一个简单的对象?
  • 有了流,你可以读一点,保存在本地磁盘上,然后重复。
  • 我不熟悉 API,但我想这不是 @ammu 的错,因为在调用 executeMediaAndDownloadTo(..) 时发生错误。可能存在大小限制,或者您可以尝试根据需要为更大的文件设置客户端内存。你的baos 不断增长,直到没有更多的内存。除非 API 提供一些读一点写一点的选项,否则我认为你是无能为力的。
  • 建议here 的可能解决方案。该代码在 python 中,您应该在 java 中有类似的方法。

标签: java google-drive-api java-io


【解决方案1】:

请参阅https://developers.google.com/api-client-library/java/google-api-java-client/media-download,其中说“当您从服务器下载大型媒体文件时,请使用可恢复媒体下载逐块下载文件”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多