Roman Kazanovskyi
Roman Kazanovskyi

Reputation: 3599

java Why file size is different with operation system

I download file from website and check the size (the same if i check size in operation system in bytes).

        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");
        }

then I tryed check stored file by other way too (NIO):

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

The result is different with size from operation system.Why?

Upvotes: 2

Views: 475

Answers (3)

Joop Eggen
Joop Eggen

Reputation: 109567

The lines

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

should be

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

Especially a BufferedOutputStream will write its buffer only when entirely filled. The last buffer is most often actually written on close() calling flush().

Upvotes: 1

Roman Kazanovskyi
Roman Kazanovskyi

Reputation: 3599

You check the file size before closing stream. I you do after closing streams you will get the same size with operation system

    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");                
    }

Upvotes: 0

Jonathan Wheeler
Jonathan Wheeler

Reputation: 2699

Binary prefixes:

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

Windows uses 1024 bytes in a kilobyte (2^10) while Linux uses 1000 bytes in a kilobyte. This propagates in MB, GB, etc...

Upvotes: 4

Related Questions