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.

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);
The size of the file: 2000 bytes

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course