Get File Size in Java

Tags: Java File Java IO Java NIO

Introduction

In this post we are going to explore how to get file size in bytes, kilobytes, megabytes or gigabytes in different Java versions.

For example we have a file located at D:\SimpleSolution\logo.png as following screenshot.

Get File Size in Java

Using NIO Files.size() method with Java version 7 and above

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class GetFileSizeExample1 {
    public static void main(String[] args) {
        try {
            String fileLocation = "D:\\SimpleSolution\\logo.png";
            Path path = Paths.get(fileLocation);

            long fileSizeInBytes = Files.size(path);
            double fileSizeInKiloBytes = fileSizeInBytes / 1024.0;
            double fileSizeInMegaBytes = fileSizeInKiloBytes / 1024.0;
            double fileSizeInGigaBytes = fileSizeInMegaBytes / 1024.0;

            System.out.println("File size: " );
            System.out.println(fileSizeInBytes + " bytes");
            System.out.println(fileSizeInKiloBytes + " KB");
            System.out.println(fileSizeInMegaBytes + " MB");
            System.out.println(fileSizeInGigaBytes + " GB");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Output:

File size: 
31281 bytes
30.5478515625 KB
0.029831886291503906 MB
2.9132701456546783E-5 GB

Using IO File.length() method with Java version older than 7

import java.io.File;

public class GetFileSizeExample2 {
    public static void main(String[] args) {
        String fileLocation = "D:\\SimpleSolution\\logo.png";
        File file = new File(fileLocation);
        if(file.exists()) {
            long fileSizeInBytes = file.length();
            double fileSizeInKiloBytes = fileSizeInBytes / 1024.0;
            double fileSizeInMegaBytes = fileSizeInKiloBytes / 1024.0;
            double fileSizeInGigaBytes = fileSizeInMegaBytes / 1024.0;

            System.out.println("File size: " );
            System.out.println(fileSizeInBytes + " bytes");
            System.out.println(fileSizeInKiloBytes + " KB");
            System.out.println(fileSizeInMegaBytes + " MB");
            System.out.println(fileSizeInGigaBytes + " GB");
        } else {
            System.out.println("File does not exists.");
        }
    }
}
Output:

File size: 
31281 bytes
30.5478515625 KB
0.029831886291503906 MB
2.9132701456546783E-5 GB

Happy Coding 😊

Apache Commons IO to get Readable File Size in KB MB GB TB

Get Absolute File Path of a File in Java