How to get a file size in Java

In Java 7+, you can use the Files.size() static method to get the size of a file in bytes. Let us say we have a logo.png image file of size ~17KB on the file system.

Using Files.size() Method

Here is an example that demonstrates how you can use Files.size() from Java's NIO API to get the file size:

try {
    // get file size in bytes
    long size = Files.size(Paths.get("logo.png"));

    // convert size to KB/MB
    double kb = size / 1024.0;
    double mb = kb / 1024.0;

    // print size
    System.out.println("Bytes: " + size);
    System.out.println("KB: " + kb);
    System.out.println("MB: " + mb);

} catch (IOException ex) {
    ex.printStackTrace();
}

The above program will output the following:

Bytes: 17335
KB: 16.9287109375
MB: 0.016531944274902344

Note: The size of a file may differ from the actual size on the file system due to compression, support for sparse files, or other reasons.

Using File.length() Method

If you can using an older version of Java (< 7), you can still get the file size simply using File.length() as shown below:

// create a file instance
File file = new File("logo.png");

// check if file exist (recommended)
if (file.exists()) {

    // get file size in bytes
    long size = file.length();

    // convert size to KB/MB
    double kb = size / 1024.0;
    double mb = kb / 1024.0;

    // print size
    System.out.println("Bytes: " + size);
    System.out.println("KB: " + kb);
    System.out.println("MB: " + mb);

}

Further Reading

You may be interested in other Java I/O articles:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.