gpt4 book ai didi

java - FileOutputStream.close 在写大文件时真的很慢

转载 作者:搜寻专家 更新时间:2023-10-31 20:15:16 26 4
gpt4 key购买 nike

我有一个方法可以使用以下代码通过 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 在接收大文件时花费很长时间,这是为什么?如您所见,我在每个接收到的 block 处刷新流..

最佳答案

根据操作系统的不同,flush() 只是强制将数据写入操作系统。对于 FileOutputStream,write() 将所有数据传递给操作系统,因此 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

从速度上可以看出,在这个系统上即使关闭也不写入数据。即驱动器不是那么快。

关于java - FileOutputStream.close 在写大文件时真的很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7849528/

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