Java File length() Method

Java File Java File


File.length()is in Javajava.io.Filea common method of the class, used to get the size of a file (in bytes). This method returns alongvalue of type, representing the byte length of the specified file.

Method Syntax

public long length()

Return Value

Returns the size of the file in bytes. If the file does not exist or is a directory, returns0L。


Use Cases

length()This method is particularly useful in the following cases:

  1. Check whether the file size meets requirements
  2. Monitor changes in file size
  3. Calculate disk space usage
  4. Display progress during file upload/download

Basic Usage Example

Example 1: Get File Size

Example

import java.io.File;

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

Code Explanation

  1. CreateFilean object pointing to the target file
  2. Check whether the file exists
  3. If it exists, calllength()the method to get the file size
  4. Print file size information

Notes

1. When the file does not exist

If the file does not exist,length()the method returns0instead of throwing an exception. Therefore, it is best to check whether the file exists before calling it:

Example

if (file.exists()) {
    long size = file.length();
    // Handle file size
} else {
    // Logic for handling non-existent file
}

2. When it is a directory

For directories,length()the method also returns0. If you need to get the size of a directory, you need to recursively calculate the sizes of all files under the directory.

3. Symbolic links

If the file is a symbolic link,length()the returned value is the size of the actual file pointed to by the link.

4. Handling large files

Sincelength()the return value islongtype, it can handle files up to 2^63-1 bytes (about 8EB), sufficient for most scenarios.


Advanced Usage

Example 2: Formatting File Size

Example

import java.io.File;

public class FileSizeFormatter {
    public static void main(String[] args) {
        File file = new File("largefile.zip");
        long size = file.length();
       
        System.out.println("Original size: " + size + " bytes");
        System.out.println("Formatted size: " + formatFileSize(size));
    }
   
    public static String formatFileSize(long size) {
        if (size < 1024) {
            return size + " B";
        }
        int exp = (int) (Math.log(size) / Math.log(1024));
        char unit = "KMGTPE".charAt(exp-1);
        return String.format("%.1f %sB", size / Math.pow(1024, exp), unit);
    }
}

Sample Output

原始大小: 1500000 字节
格式化大小: 1.4 MB

Performance Considerations

File.length()The method call is lightweight because it only queries the metadata of the file system and does not actually read the file content. However, you need to pay attention in the following cases:

  1. Network file system: Accessing metadata on a remote file system may have latency
  2. Frequent calls: If you need to frequently get file sizes, consider caching the results
  3. Real-time monitoring: For scenarios where you need to monitor file size changes in real time, you may need to combineWatchServiceuse

FAQ

Q1: Why does calling length() on a directory return 0?

A: In most file systems, a directory itself does not occupy storage space (or occupies a fixed small space). The `length()` method is designed to return 0 for directories.

Q2: Does the length() method block?

A: Generally no, unless accessing a network file system with poor network conditions.

Q3: How to get the total size of a directory?

A: You need to recursively traverse all files in the directory and accumulate their `length()` values.

Summary

File.length()It is a simple but practical method for obtaining file size information. When using it, you need to pay attention to edge cases such as whether the file exists and whether it is a directory. Combined with other file operation methods, you can build powerful file processing functionality.

Java File Java File

Other Extensions