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

Output

Note:

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.

Output

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.

Tags
Join 1000+ fellow learners! Enter your email address below: