Problems reading a huge file of 12 MB (java.lang.OutOfMemoryError)

懵懂的女人 提交于 2019-12-07 16:10:15

问题


i need to open a file of 12 Megabytes, but actually i'm doing it creating a buffer of 12834566-byte, because the size of the file is 12MB and i am developing this app for Android mobile systems.

Then, i supose i have to read with blocks of 1024 Kbytes instead of one block of 12 Mbytes, with a for, but i don't know how to do it, i need a little help with it.

This is my actual code:

File f = new File(getCacheDir()+"/berlin.mp3");
        if (!f.exists()) try {
          InputStream is = getAssets().open("berlin.mp3");
          int size = is.available();
          byte[] buffer = new byte[size];
          is.read(buffer);
          is.close();
          FileOutputStream fos = new FileOutputStream(f);
          fos.write(buffer);
          fos.close();
        } catch (Exception e) { throw new RuntimeException(e); }

Please, can someone tell me what i have to changue in this code to read blocks of 1024 Kbytes instead of one block of 12 Mbytes?

THanks!


回答1:


Try copying 1 KB at a time.

File f = new File(getCacheDir()+"/berlin.mp3");
if (!f.exists()) try {
     byte[] buffer = new byte[1024];
     InputStream is = getAssets().open("berlin.mp3");
     FileOutputStream fos = new FileOutputStream(f);
     int len;
     while((len = is.read(buffer)) > 0) 
        fos.write(buffer, 0, len);
} catch (Exception e) { 
     throw new RuntimeException(e); 
} finally {
     IOUtils.close(is); // utility to close the stream properly.
     IOUtils.close(fos);
}

Does Android support symbolic or hand links like UNIX? If it does, this would be faster/more efficient.




回答2:


File f = new File(getCacheDir()+"/berlin.mp3");
InputStream is = null;
FileOutputStream fos = null;
if (!f.exists()) try {
    is = getAssets().open("berlin.mp3");
    fos = new FileOutputStream(f);
    byte[] buffer = new byte[1024];
    while (is.read(buffer) > 0) {
        fos.write(buffer);
    }
} catch (Exception e) { 
    throw new RuntimeException(e); 
} finally { 
    // proper stream closing
    if (is != null) {
        try { is.close(); } catch (Exception ignored) {} finally {
           if (fos != null) {
               try { fos.close(); } catch (Exception ignored2) {}
           }
        }
    }
}



回答3:


        import org.apache.commons.fileupload.util.Streams;

        InputStream in = getAssets().open("berlin.mp3");
        OutputStream out = new FileOutputStream(f);
        Streams.copy(in, out, true);


来源:https://stackoverflow.com/questions/8477669/problems-reading-a-huge-file-of-12-mb-java-lang-outofmemoryerror

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