Files.size() for File Size
You'll learn how to retrieve the size of a file in bytes using the NIO.2 API and handle cases where the file doesn't exist.
Understanding File Size Retrieval
When working with files, you often need to know how large they are—perhaps to validate uploads, estimate processing time, or display information to users. The Files.size() method from the NIO.2 API provides a straightforward way to get a file's size in bytes.
Think of Files.size() as checking the weight of a package before shipping it. You need precise information about what you're working with.
Using Files.size()
The method signature is simple:
long size = Files.size(Path path) throws IOException
It returns a long representing the file size in bytes. You must handle IOException, which occurs when the file doesn't exist, isn't accessible, or an I/O error happens.
Here's a practical example:
import java.nio.file.*;
import java.io.IOException;
Path filePath = Paths.get("document.txt");
try {
long bytes = Files.size(filePath);
System.out.println("File size: " + bytes + " bytes");
// Convert to KB for readability
double kilobytes = bytes / 1024.0;
System.out.println("File size: " + kilobytes + " KB");
} catch (IOException e) {
System.err.println("Unable to retrieve file size: " + e.getMessage());
}
The IOException catches problems like non-existent files, permission issues, or I/O failures. Always wrap Files.size() in a try-catch block.
Key Takeaway: Files.size(Path) returns a file's size in bytes as a long, and you must handle IOException for missing or inaccessible files.