Java java.nio.file.Files size() Method

Java File Java java.nio.file.Files


java.nio.file.Files.size()is a very practical static method in the Java NIO (New I/O) package, used to get the size of a specified file (in bytes). This method belongs to thejava.nio.filepackage, and is part of the file operation API introduced in Java 7.

Method Definition

public static long size(Path path) throws IOException

Method Parameters

Path path

  • Type: java.nio.file.Path
  • Description: The file path object whose size is to be obtained
  • Note:
    • Must point to an actually existing file
    • Cannot be a directory (otherwise an exception will be thrown)
    • The path can be an absolute path or a relative path

Return Value

long type

  • Meaning: Returns the size of the file, in bytes
  • Characteristics:
    • If the file is empty, returns 0
    • For large files, the return value may exceedInteger.MAX_VALUE

Exception Handling

size()The method may throw the following exceptions:

IOException

  • Trigger Conditions:
    • File does not exist
    • No permission to read the file
    • An input/output error occurs
    • The path points to a directory rather than a file

SecurityException

  • Trigger Condition: When a security manager exists and denies access to the file

Usage Examples

Basic Usage

Example

import java.nio.file.*;
import java.io.IOException;

public class FileSizeExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("example.txt");
       
        try {
            long fileSize = Files.size(filePath);
            System.out.println("File size: " + fileSize + " bytes");
        } catch (IOException e) {
            System.err.println("Error getting file size: " + e.getMessage());
        }
    }
}

Handling Large Files

Example

// For files that may be very large, consider using a more user-friendly display format
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);
}

Notes

  1. Performance Considerations:

    • For local file systems,size()the operation is usually fast
    • For network file systems, there may be latency
  2. Symbolic Links:

    • If the path is a symbolic link, the size of the actual file pointed to by the link is returned
  3. File Locking:

    • The method does not lock the file during execution, so the file size may change immediately after being obtained
  4. Alternatives:

    • For older Java versions, you can usejava.io.File.length()

Practical Application Scenarios

Checking before file upload:

Example

// Check whether the file exceeds the allowed size
if (Files.size(filePath) > MAX_UPLOAD_SIZE) {
    throw new FileTooLargeException();
}

Disk Space Management:

Example

// Calculate the total size of all files under a directory
long totalSize = Files.walk(dirPath)
                    .filter(Files::isRegularFile)
                    .mapToLong(Files::size)
                    .sum();

Progress Display:

Example

// Display file copy progress
long totalBytes = Files.size(sourcePath);
long copiedBytes = 0;
// ...Update and display progress percentage in the copy loop...

Frequently Asked Questions

Q1: Can the size() method be used on directories?

No. If the path points to a directory, it will throwIOException. To get the directory size, you need to useFiles.walk()Traverse the directory contents and accumulate file sizes.

Q2: Does this method block?

For local file systems it usually does not block noticeably, but for network file systems there may be latency.

Q3: Why is the return type long instead of int?

Because some files may exceed 2GB (Integer.MAX_VALUE), using long can support very large files.

Q4: What is the difference between this method and File.length()?

Files.size()is part of the NIO.2 API and supports more modern file system features (such as symbolic links), whileFile.length()is a method of traditional I/O.


Summary

java.nio.file.Files.size()The method provides a simple and effective way to get the file size, and is a commonly used utility method in file operations. Understanding its usage and potential exceptions is very important for writing robust file processing code.

Java File Java java.nio.file.Files

Other Extensions