Upload large files to the Google Drive

前提是你 提交于 2019-12-10 11:10:33

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/42698519/upload-large-files-to-the-google-drive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!