How do I get file size in Java?

This example will show you how to get the size of a file. To obtain the size of a file you can use the File‘s length() method. The length() method return the file size in bytes.



public class FileSize {
    public static void main(String[] args) throws Exception {
        File file = new File("");

        // Get the size of a file in bytes.
        long fileSize = file.length();

        // Using Java printf() method to print the file size
        System.out.printf("File size: %,d bytes.%n", fileSize);

This will print something like:

File size: 51,981 bytes.

If you want to format the file size in Kilobytes, Megabytes or Gigabytes check the following example How do I create a human-readable file size?.

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.