gpt4 book ai didi

android - 将 BufferedInputStream 转换为文件

转载 作者:太空宇宙 更新时间:2023-11-03 13:35:53 26 4
gpt4 key购买 nike

我正在从网络加载图像到本地 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 分钟。有什么办法可以优化这个吗?

最佳答案

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

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

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

您应该尝试使用 array version of read()取而代之的是:read(byte[] buffer, int offset, int byteCount),数组和我上面描述的一样大。

关于android - 将 BufferedInputStream 转换为文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7420476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com