Java Code Examples for java.nio.file.Files.size()

More Java code examples for java.nio.file.Files

Java Code Example 1 - Get File Size

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

Get File Size in Java

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