Java IO

Get file size in Java example

Get file size in Java example shows how to get file size in Java. Example also shows how to get file size in bytes, KB, MB, GB and TB in Java.

How to get file size in Java?

You can use Java File class to get the file size. File class provides length method which returns file’s size in bytes.

This method returns size of the file in bytes.

Java File Size Example



If the file does not exists, length method returns 0. To differentiate it with the actually empty file, always check if the file exists using exists method of the File class before getting the file size.

How to get file size in KB, MB, GB and TB in Java?

Once you get the file size in bytes, it is fairly easy to convert it to kilobytes (KB), megabytes (MB), gigabytes (GB) and terabytes (TB) as given below.


Important Note:

File length method throws SecurityException if the file is not readable or there is no read access.

Please let us know your views in the comments section below.

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.


About the author



rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *