Convert a BufferedInputStream to a File

vikramjb picture vikramjb · Sep 14, 2011 · Viewed 7.7k times · Source

I am loading a image from the web to the local android phone. The code that I have for writing to a file is as follows

        BufferedInputStream bisMBImage=null;
        InputStream isImage = null;
        URL urlImage = null;
        URLConnection urlImageCon = null;
        try 
        {
                urlImage = new URL(imageURL); //you can write here any link
                urlImageCon = urlImage.openConnection();
                isImage = urlImageCon.getInputStream();
                bisMBImage = new BufferedInputStream(isImage);

                int dotPos = imageURL.lastIndexOf(".");
                if (dotPos > 0 )
                {
                    imageExt = imageURL.substring(dotPos,imageURL.length());    
                }

                imageFileName = PATH + "t1" + imageExt;
                File file = new File(imageFileName);
                if (file.exists())
                {
                    file.delete();
                    Log.d("FD",imageFileName + " deleted");
                }
                 ByteArrayBuffer baf = new ByteArrayBuffer(255);
                 Log.d("IMAGEWRITE", "Start to write image to Disk");
                 int current = 0;
                 try 
                 {
                    while ((current = bisMBImage.read()) != -1) 
                    {
                             baf.append((byte) current);
                    }

                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(baf.toByteArray());
                    fos.close();    
                    Log.d("IMAGEWRITE", "Image write to Disk done");
                } 
                catch (IOException e) 
                {
                    e.printStackTrace();
                }                       

                isImage.close();
        } 
        catch (IOException e) 
        {
                Log.d("DownloadImage", "Error: " + e);
        }
        finally
        {
            isImage = null;         
            urlImageCon = null;
            urlImage = null;
        }

For some reason the whole writing to a file takes 1 minute. Is there a way I can optimize this ?

Answer

Shlublu picture Shlublu · Sep 14, 2011

Your buffer is very small: 255 bytes. You could make it 1024 times bigger (255 kilobytes). This is an acceptable size and this would certainly speed up the thing.

Also, this is very slow as it reads the bytes one by one:

while ((current = bisMBImage.read()) != -1)  {
    baf.append((byte) current);
}

You should try using the array version of read() instead: read(byte[] buffer, int offset, int byteCount) with an array as large as what I have described above.