我正在从web加载图像到本地android手机。我写入文件的代码如下将BufferedInputStream转换为文件
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分钟。有什么方法可以优化这个吗?
这是一个很大的图像吗? – Otra
与奥特拉所要求的相似 - 图像有多大?此外,我看到你已经把'android-emulator'标签放在这个问题上 - 虽然我不使用它,但模拟器对于某些东西可能会很慢,所以我不确定它是否包含文件下载/写入。你有没有在真实设备上试过这个,看看需要多长时间? – Squonk
这是在主UI线程还是在单独的线程中运行? – WindsurferOak