3

我正在将图像从网络加载到本地 android 手机。我写入文件的代码如下

        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;
        }

由于某种原因,整个写入文件需要 1 分钟。有没有办法可以优化这个?

4

2 回答 2

2

您的缓冲区非常小:255 字节。你可以让它大 1024 倍(255 KB)。这是一个可以接受的大小,这肯定会加快速度。

此外,这非常慢,因为它一个一个地读取字节:

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

您应该尝试使用read() 的数组版本read(byte[] buffer, int offset, int byteCount)使用与我上面描述的一样大的数组。

于 2011-09-14T17:36:59.637 回答
2

您应该使用 Android HttpClient 通过 java URL 连接获取文件。您的缓冲区也非常小。试试这个剪断:

FileOutputStream f = new FileOutputStream(new File(root,"yourfile.dat"));

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
InputStream is = response.getEntity().getContent();

byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = is.read(buffer)) > 0 ) {
        f.write(buffer,0, len1);
}
f.close();
于 2011-09-14T17:44:54.943 回答