写入大文件时,FileOutputStream.close确实很慢

我有一个使用此代码通过TCP套接字接收文件的方法:

FileOutputStream fileStream = new FileOutputStream(filename.getName());

while (totalRead < size) {

if (size - totalRead > CHUNKSIZE) {

read = getInputStream().read(buffer, 0, CHUNKSIZE);

} else {

read = getInputStream().read(buffer, 0, size - totalRead);

}

totalRead += read;

fileStream.write(buffer, 0, read);

fileStream.flush();

if (System.currentTimeMillis() > nextPrint) {

nextPrint += 1000;

int speed = (int) (totalRead / (System.currentTimeMillis() - startTime));

double procent = ((double)totalRead / size) * 100;

gui.setStatus("Reciving: " + filename + " at " + speed + " kb/s, " + procent + "% complete");

}

}

gui.setStatus("Reciving: " + filename + " complete.");

fileStream.close();

接收大文件时,FileOutputStream.close会花费很长时间,这是为什么呢?如您所见,我正在每个接收到的块上刷新流。

回答:

根据操作系统的不同,flush()仅需强制将数据写入操作系统即可。对于FileOutputStream,write()将所有数据传递给OS,因此flush()不会执行任何操作。凡为close()能确保文件实际写入到磁盘(或不依赖于操作系统而定)。您可以在写入数据时查看磁盘是否仍然繁忙。

500 MB的文件耗时30秒,表示您正在写入17 MB / s。这听起来像磁盘非常慢,或者网络共享/驱动器中的文件。


你可以试试这个

File file = File.createTempFile("deleteme", "dat"); // put your file here.

FileOutputStream fos = new FileOutputStream(file);

long start = System.nanoTime();

byte[] bytes = new byte[32 * 1024];

for (long l = 0; l < 500 * 1000 * 1000; l += bytes.length)

fos.write(bytes);

long mid = System.nanoTime();

System.out.printf("Took %.3f seconds to write %,d bytes%n", (mid - start) / 1e9, file.length());

fos.close();

long end = System.nanoTime();

System.out.printf("Took %.3f seconds to close%n", (end - mid) / 1e9);

版画

Took 0.116 seconds to write 500,006,912 bytes

Took 0.002 seconds to close

从速度上您可以看到,即使在关闭状态下,该系统也无法写入数据。即驱动器不是那么快。

以上是 写入大文件时,FileOutputStream.close确实很慢 的全部内容, 来源链接: utcz.com/qa/431887.html

回到顶部