Detailed explanation and example code of obtaining file size in Java
Java get file size
Today, when writing code, you need to realize the function of obtaining file size. At present, there are two implementation methods. One is to use the length () method of file; The other is to use the available () method of FileInputStream. When InputStream does not perform read operation, the size of available () should be equal to the file size. However, when dealing with large files, the latter will have problems. Let's take a look:
In the example, I used the installation image file of CentOS 6.5, mainly considering that the file is large enough (greater than 2GB).
1. Use the length () method of file
Let's look at the output:
four billion four hundred and sixty-seven million nine hundred and eighty-two thousand three hundred and thirty-six
The result is 4.16gb, which is consistent with the result displayed on windows.
Next, let's take a look at the file size obtained through FileInputStream:
Here are the results:
two billion one hundred and forty-seven million four hundred and eighty-three thousand six hundred and forty-seven
Does the result look familiar? It is integer MAX_ Value is the maximum value that a signed integer can represent.
How big is the file size obtained in this way when converted to familiar units?
About 2GB, which is obviously not the correct result.
The reason is that the type returned by the length () method of file is long, and the maximum positive number that can be represented by the long type is 9223372036854775807, which is converted into the maximum supported file size of 8954730132868714 EB bytes. This magnitude will be used for many years in the history of human it development, while the return value of the available () method of FileInputStream is int, The maximum representation range was also introduced before. The maximum file size that can be supported is 1.99GB, which is easy to reach now.
Added on March 31, 2014:
It is not impossible to read large file size by streaming method, but the traditional Java io.* The next package, here we need to use Java nio.* A new tool under - filechannel. Let's look at the following example code:
The results obtained after using filechannel are consistent with the first case, which accurately describes the exact size of the file.
Here we also remind our technical colleagues that when it comes to reading large files, we must pay attention to the int type data to avoid hidden bugs, which is very difficult to locate.
Thank you for reading, hope to help you, thank you for your support to this site!