0
0
JavaHow-ToBeginner · 3 min read

How to Get File Size in Java: Simple Guide with Examples

In Java, you can get the size of a file by creating a File object and calling its length() method, which returns the file size in bytes. For example, long size = new File("path/to/file").length(); gives you the file size as a long value.
📐

Syntax

The basic syntax to get a file size in Java is:

  • File file = new File("path/to/file"); - creates a File object for the file path.
  • long size = file.length(); - returns the size of the file in bytes as a long value.

If the file does not exist, length() returns 0.

java
import java.io.File;

File file = new File("path/to/file");
long size = file.length();
💻

Example

This example shows how to get the size of a file named example.txt and print its size in bytes.

java
import java.io.File;

public class FileSizeExample {
    public static void main(String[] args) {
        File file = new File("example.txt");
        if (file.exists()) {
            long size = file.length();
            System.out.println("File size: " + size + " bytes");
        } else {
            System.out.println("File does not exist.");
        }
    }
}
Output
File size: 1234 bytes
⚠️

Common Pitfalls

Common mistakes when getting file size in Java include:

  • Not checking if the file exists before calling length(). If the file does not exist, length() returns 0, which can be misleading.
  • Confusing file size with available disk space or directory size. The length() method only works for files, not directories.
  • Using relative paths without knowing the current working directory, which can cause File to point to the wrong file.
java
import java.io.File;

public class WrongFileSize {
    public static void main(String[] args) {
        File file = new File("nonexistent.txt");
        // Wrong: no check for existence
        System.out.println("Size: " + file.length()); // prints 0, but file doesn't exist

        // Right way:
        if (file.exists()) {
            System.out.println("Size: " + file.length());
        } else {
            System.out.println("File not found.");
        }
    }
}
Output
Size: 0 File not found.
📊

Quick Reference

Summary tips for getting file size in Java:

  • Use File.length() to get size in bytes.
  • Always check File.exists() before reading size.
  • Remember length() returns 0 for directories or non-existent files.
  • File size is returned as a long to handle large files.

Key Takeaways

Use the File class and its length() method to get file size in bytes.
Always check if the file exists before calling length() to avoid misleading results.
length() returns 0 for directories or files that do not exist.
File size is returned as a long value to support large files.
Use absolute or correct relative paths to avoid file not found issues.