Easy Tutorial
❮ Java Arraylist Remove Collection Replace ❯

Java Example - Get File Size

Java Example

The following example demonstrates how to get the file size in bytes (1KB = 1024 bytes) using the file.exists() and file.length() methods of the File class:

Main.java File

import java.io.File;

public class Main {
    public static long getFileSize(String filename) {
        File file = new File(filename);
        if (!file.exists() || !file.isFile()) {
            System.out.println("File does not exist");
            return -1;
        }
        return file.length();
    }
    public static void main(String[] args) {
        long size = getFileSize("c:/java.txt");
        System.out.println("java.txt file size is: " + size);
    }
}

The above code outputs the following result when the java.txt file is located on the C drive:

java.txt file size is: 480

Java Example

❮ Java Arraylist Remove Collection Replace ❯