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.

package org.kodejava.io;

import java.io.File;

public class FileSize {
    public static void main(String[] args) {
        File file = new File("README.md");

        // 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

Leave a Reply

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