java为什么文件大小与操作系统不同

时间:2014-12-10 16:06:22

标签: java

我从网站下载文件并检查大小(如果我在操作系统中检查大小,则以字节为单位)。

        connection.getContentLength();
        int sizeBefore = connection.getContentLength();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(connection.getInputStream());
        File destFile = new File(destFileName);
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
                new FileOutputStream(destFile));

        while ((i = bufferedInputStream.read()) != -1) {
                bufferedOutputStream.write(i);               
        }
        long sizeAfter = destFile.length(); 
        bufferedOutputStream.flush();
        bufferedInputStream.close();

        if (sizeAfter == sizeBefore) {
            log.debug("Downloaded file correct");
        }

然后我也尝试通过其他方式检查存储文件(NIO):

long size =  Files.size(destFile.toPath())));

结果与操作系统的大小不同。为什么?

3 个答案:

答案 0 :(得分:4)

二进制前缀:

http://en.wikipedia.org/wiki/Binary_prefix#Adoption_by_IEC_and_NIST

Windows使用1024字节(千字节(2 ^ 10))而Linux使用1000字节(千字节)。这以MB,GB等传播......

答案 1 :(得分:1)

    long sizeAfter = destFile.length(); 
    bufferedOutputStream.flush();
    bufferedInputStream.close();

应该是

    bufferedOutputStream.close(); // Close the file. Flushes too.
    bufferedInputStream.close();
    long sizeAfter = destFile.length(); // Check its size on disk.

特别是BufferedOutputStream只在完全填充时才会写入缓冲区。 最后一个缓冲区通常实际上是close()调用flush()

答案 2 :(得分:0)

在关闭流之前检查文件大小。关闭流后,您将使用操作系统获得相同的大小

    connection.connect();
    int sizeBefore =  connection.getContentLength();
    BufferedInputStream bufferedInputStream = new BufferedInputStream(connection.getInputStream());
    File destFile = new File (destFileName);
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
            new FileOutputStream(destFile));
    while ((i = bufferedInputStream.read()) != -1) {
        bufferedOutputStream.write(i);
    }
    bufferedOutputStream.flush();
    bufferedInputStream.close();
    long sizeAfter = destFile.length();
    if (sizeAfter==sizeBefore) {
        log.info("Downloaded correct");                
    }