[英]FileOutputstream.close() is not always writing bytes to file system?
[英]FileOutputStream.close is really slow when writing large file
我有一個使用此代碼通過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
從速度上您可以看到,即使在關閉狀態下,該系統也無法寫入數據。 即驅動器不是那么快。
我在使用filestream時也看到了同樣的情況。 我發現,如果您以讀寫方式打開文件,它會緩存所有內容,直到關閉或處置后才寫入。 同花順沒有寫。 但是,如果您的寫操作擴展了文件的大小,它將自動刷新。
每次寫入都會自動刷新為剛剛寫入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.