简体   繁体   中英

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

I am using google drive JAVA SDK API to download the files below is the code, getGoogleDriveServiceInstance() method will return Drive instance in the below code. This code works perfect for small files but but for files > 500 MB i am getting Out of Memory Error, I need some help how to fix this issue.

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;
    }

If the file size is big, below error is coming->

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 ,其中显示“当您从服务器下载大型媒体文件时,请使用可恢复的媒体下载进行下载逐个文件”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM