首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >写入文件系统的时间太长了

写入文件系统的时间太长了
EN

Stack Overflow用户
提问于 2018-06-05 06:31:50
回答 1查看 742关注 0票数 0

我试图下载大约300-400个图像文件,使用最优线程数(大约20-30个),然后将这些图像写入Android的文件系统中。问题是整个过程要花费10-13分钟,我想用高速互联网来计时2-3分钟。

我认为这是可以实现的,因为300-400图像文件的大小仅在一些KBs中(总大小约为80-100 MB)。

这是我下载和保存文件的代码

代码语言:javascript
复制
            long t1 = System.currentTimeMillis();

            Call<ResponseBody> call=apiService.fetchAttachmentDetail(att_id,token,true,device_id, 0.0f, 0.0f);

            Response<ResponseBody> response = call.execute();
            long t2 = System.currentTimeMillis();
            Help.E("downloaded " + att_id + "and time taken in mili second " + (t2 - t1));
            Help.E("content length- " + response.body().contentLength());

            String str = response.headers().get("Content-Type");
            if (str == null)
                str = "/png";
            String ext_type = str.substring(str.indexOf("/") + 1);
            InputStream in = null;
            FileOutputStream out = null;
            ContextWrapper cw = new ContextWrapper(context);
            String fileName = "";
            File directory = cw.getDir(AttachmentDirName, Context.MODE_PRIVATE);
            try {
                in = response.body().byteStream();
                fileName = String.valueOf(att_id) + "." + ext_type;
                File file = new File(directory, fileName);
                out = new FileOutputStream(file);

                int c;
                while ((c = in.read()) != -1) {
                    out.write(c);
                }
            } catch (IOException e) {
                Log.d("Error", e.toString());
                emitter.onError(e);
            } finally {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            }

            long t3 = System.currentTimeMillis();

            Help.E("saved " + att_id + "time taken in saving the file " + (t3 - t2));
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-05 06:56:23

您正在逐字节地读取和写入数据,这比使用缓冲区读取和写入数据要花费更多的时间。尝试使用以下方法:

代码语言:javascript
复制
public static void copyStream(InputStream input, OutputStream output)
    throws IOException
{
    byte[] buffer = new byte[1024]; // Adjust if you want
    int bytesRead;
    while ((bytesRead = input.read(buffer)) != -1)
    {
        output.write(buffer, 0, bytesRead);
    }
}

所以你换了你的

代码语言:javascript
复制
int c;
while ((c = in.read()) != -1) {
   out.write(c);
}

使用

代码语言:javascript
复制
copyStream(in, out);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50693490

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档