Java File Size Example

In this source code example, we show you how to find the size of the file in Java.

We use Files.size() method to calculate the size of the given file.

Files.size() method

This method returns the size of a file (in bytes). The size may differ from the actual size of the file system due to compression, support for sparse files, or other reasons. The size of files that are not regular files is implementation-specific and therefore unspecified.

Java File Size Example

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

public class JavaFileSize {

    public static void main(String[] args) throws IOException {
        
        Path myPath = Paths.get("src/resources/bugs.txt");
        
        long fileSize = Files.size(myPath);
        
        System.out.format("File size: %d bytes%n", fileSize);
    }
}

References


Comments