5

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

4

2 回答 2

3

根据操作系统,flush()没有什么比强制将数据写入操作系统的了。在 FileOutputStream 的情况下,write() 将所有数据传递给操作系统,因此 flush() 什么也不做。哪里close()可以确保文件实际写入磁盘(或不取决于操作系统)。写数据的时候可以看看磁盘是否还在忙。

一个需要 30 秒的 500 MB 文件意味着您正在写入 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

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

于 2011-10-21T13:17:11.513 回答
1

我在使用文件流时看到了同样的情况。我发现如果您以读写方式打开文件,它会缓存所有内容并且在您关闭或处置之前不会写入。冲洗没有写。但是,如果您的写入扩展了文件的大小,它将自动刷新。

每次写入时都以写入方式打开。

于 2011-12-30T22:55:05.443 回答