raju
raju

Reputation: 1264

Out Of Memory Exception

In my app i am giving video file path to FileInputStream class after that i want it to convert into byte Array but it throws Out of memory Exception Please suggest me how to do it.Iam posting the code here thanks in advance.

public byte[] readBytes(InputStream inputStream) throws IOException
{       
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();  
    int bufferSize = 1024;     
    byte[] buffer = new byte[bufferSize];    
    int len = 0;    
    while ((len = inputStream.read(buffer)) != -1) 
    {         
       byteBuffer.write(buffer, 0, len);   
    }       
    return byteBuffer.toByteArray();
}  

Upvotes: 1

Views: 4718

Answers (2)

Caner
Caner

Reputation: 59150

It fails because on the device you are testing you are allowed to use about 20MB of heap. At the time it fails, your app is already using 13.5MB of memory. When you are trying to convert ByteArrayOutputStream to byte array it is trying to allocate a new ~7MB size byte[] which fails because there is not enough memory. One workaround is to avoid this new allocation by reusing internal byte[] of ByteArrayOutputStream. Unfortunately there is no way to access it externally, so you need to create your own way like this:

First create MyByteArrayOutputStream.java:

public MyByteArrayOutputStream extends ByteArrayOutputStream {
    @Override
    public synchronized byte[] toByteArray() {
        return buf;
    }
}

And in your code:

public byte[] readBytes(InputStream inputStream) throws IOException
{       
    MyByteArrayOutputStream byteBuffer = new MyByteArrayOutputStream(); // note the change!
    int bufferSize = 1024;     
    byte[] buffer = new byte[bufferSize];    
    int len = 0;    
    while ((len = inputStream.read(buffer)) != -1) 
    {         
       byteBuffer.write(buffer, 0, len);   
    }
    inputStream.close(); // hopefully this will release some more memory
    return byteBuffer.toByteArray();
}

Note that, this will still fail with large videos. Optimally you should try to upload big files in smaller chunks.

Upvotes: 4

talkol
talkol

Reputation: 12887

Seems straight forward, the video file is too large to fit in memory. Are you 100% certain you need to place the whole file in memory? This is usually a bad design concept.

Upvotes: 0

Related Questions