Reputation: 3599
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
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
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
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