写入文件系统花费的时间太长

时间:2018-06-05 06:31:51

标签: android multithreading performance io storage

我尝试使用最佳线程数(大约20-30)下载大约300-400个图像文件,然后将这些图像写入Android的文件系统。问题是整个过程需要10-13分钟,我希望用高速互联网计算大约2-3分钟 我认为这可以实现,因为这些300-400图像文件的大小仅为一些KB(总大小约为80-100 MB)
这是我下载和保存文件的代码

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

1 个答案:

答案 0 :(得分:1)

您正逐字节地读取和写入数据,与使用缓冲区读取和写入相比,所需的时间要长得多。尝试使用此方法:

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

所以你要替换

int c;
while ((c = in.read()) != -1) {
   out.write(c);
}

copyStream(in, out);