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.