简体   繁体   中英

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

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!

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.

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) {}
           }
        }
    }
}
        import org.apache.commons.fileupload.util.Streams;

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

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