Question

I'm downloading video files that are larger than the memory space that Android apps are given. When they're *on the device, the MediaPlayer handles them quite nicely, so their overall size isn't the issue. The problem is that if they exceed the relatively small number of megabytes that a byte[] can be then I get the dreaded OutOfMemory exception as I download them.

My intended solution is to just write the incoming byte stream straight to the SD card, however, I'm using the Apache Commons library and the way I'm doing it tries to get the entire video read in before it hands it back to me.

My code looks like this:

HttpClient client = new HttpClient();
    PostMethod filePost = new PostMethod(URL_PATH);
    client.setConnectionTimeout(timeout);
    byte [] ret ;
    try{                        
        if(nvpArray != null)
            filePost.setRequestBody(nvpArray);                   
    }catch(Exception e){
        Log.d(TAG, "download failed: " + e.toString());
    }              
    try{            
        responseCode = client.executeMethod(filePost);          
        Log.d(TAG,"statusCode>>>" + responseCode);
        ret = filePost.getResponseBody();
....     

I'm curious what another approach would be to get the byte stream one byte at a time and just write it out to disk as it comes.

Was it helpful?

Solution

You should be able to use the GetResponseBodyAsStream method of your PostMethod object and stream it to a file. Here's an untested example....

InputStream inputStream = filePost.getResponseBodyAsStream();
FileInputStream outputStream = new FileInputStream(destination);

// Per your question the buffer is set to 1 byte, but you should be able to use
// a larger buffer.
byte[] buffer = new byte[1]; 
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1)
{
    outputStream.write(buffer, 0, bytesRead);
}

outputStream.close();
inputStream.close();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top