Java Inputstream读取1.5mb文件太慢

时间:2016-06-06 11:47:05

标签: java inputstream fileinputstream bufferedinputstream

我正在研究项目的一部分。这对我这样的新手来说非常重要。在一个部分中,我必须从电子邮件中获取附件并将​​其保存到系统文件中。但由于某种原因,它花了太长时间。我将此代码用于第一种方法:

byte[] buf = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buf)) != -1) {
    fileOutputStream.write(buf, 0, bytesRead);
}

此代码块大约需要86秒才能获得1.5Mb文件。但是,当我尝试从示例测试项目中运行相同的代码时,它在几毫秒内完成(为此我将系统文件的输入流而不是附件,然后将其写入另一个目录)。 我已经访问过这个页面: Java: InputStream too slow to read huge files

Input stream reads large files very slowly, why?

但我无法找出具体原因。 我尝试通过这种方法进行更多调试:

InputStream inputStream = bodyPart.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(file);
long tStart = System.currentTimeMillis();
byte[] buf = new byte[4096];
int bytesRead;
int i=1;
while(true)
{
    long tc = System.currentTimeMillis();
    bytesRead = inputStream.read(buf);
    long tc1 = System.currentTimeMillis();
    System.out.println("\nRead Time "+i+" ="+(tc1-tc));

    if(bytesRead==-1) break;
    fileOutputStream.write(buf, 0, bytesRead);

    long tc2 = System.currentTimeMillis();
    System.out.println("Write Time "+i+" ="+(tc2-tc1));
    i++;
}

long tEnd = System.currentTimeMillis();
long tDelta = tEnd - tStart;
System.out.println("\n\nTotal Time="+tDelta+"\n\n");

输出也很奇怪。 1.5Mb文件的输出的一部分是:

Read Time 354 =788
Write Time 354 =0

Read Time 355 =0
Write Time 355 =0

Read Time 356 =0
Write Time 356 =0

Read Time 357 =744
Write Time 357 =0

Read Time 358 =0
Write Time 358 =0

Read Time 359 =0
Write Time 359 =0

Read Time 360 =837
Write Time 360 =0

Read Time 361 =0
Write Time 361 =0

Read Time 362 =1
Write Time 362 =0

Read Time 363 =811
Write Time 363 =0

Read Time 364 =1
Write Time 364 =0

Read Time 365 =0
Write Time 365 =0

Read Time 366 =757
Write Time 366 =0

Read Time 367 =1
Write Time 367 =0

Read Time 368 =0
Write Time 368 =0

Read Time 369 =736
Write Time 369 =0

Read Time 370 =0
Write Time 370 =0

Read Time 371 =0
Write Time 371 =0

Read Time 372 =484
Write Time 372 =0

Read Time 373 =0

Total Time=88796

在这里,正如您所看到的,4Kb缓冲区的读取时间在每3步或读取后需要很长时间。我无法弄清楚具体问题。我也使用了缓冲输入流和输出流,但结果是一样的。任何人都可以帮我找出实际问题是什么?

1 个答案:

答案 0 :(得分:-1)

使用bufferedinputstream而不是InputStream。