Java file size with File.length()

The length() method of File returns the file size. This is the oldest API to find out the size of a file in Java.

Java file size with File

The code example determines the file size using the File's length() method.
import java.io.File;

public class JavaFileSizeEx {
    
    public static void main(String[] args) {
        
        String fileName = "src/main/resources/words.txt";
        
        File f = new File(fileName);
        long fileSize = f.length();
        
        System.out.format("The size of the file: %d bytes", fileSize);
    }
}
Output:
The size of the file: 2000 bytes

Comments