Skip to content

Get file size in Java example

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

How to get file size in Java?

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

This method returns the size of the file in bytes.

Example

Output

Note:

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

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

Once we 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:

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

This example is a part of the Java File tutorial.

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

About the author

Leave a Reply

Your email address will not be published.