Learn to check the file size or a directory size in Java using IO classes File, Files, and Common IO’s FileUtils class.
File file = new File("...");
// Check Size
long bytes = file.length(); //1
long bytes = Files.size(file.toPath()); //2
long bytes = FileUtils.sizeOf(file); //3
// Display Size
FileUtils.byteCountToDisplaySize(2333444l);
1. Check File Size using File.length()
To get the size of the file, java.io.File class provides length()
a method that returns the file’s length in bytes.
- We may get
SecurityException
if the read access to the file is denied. - If the file represents a directory then the return value is unspecified.
File file = new File("c:/temp/demo.txt");
long bytes = file.length();
2. Check File Size using Files.size()
The Files
class provides a straightforward method size()
that acts similar to the previous example. It also returns the size of the file in bytes.
The size may differ from the actual size of the file system due to compression, support for sparse files, or other reasons. This method may also throw SecurityException if the read access to the file is denied.
File file = new File("c:/temp/demo.txt");
long bytes = Files.size(file.toPath());
3. Check File Size using Commons IO’s FileUtils.sizeOf()
FileUtils.sizeOf()
can be used to get the size of a file or directory.
- If the file is a regular file then the size of the file is returned in bytes.
- If the file is a directory then the size of the directory is calculated recursively. Note that if there is any issue in reading any file or sub-directory then its size will not be included in the result.
We should be careful to check that directory shall not too big because sizeOf()
will not detect any overflow in the final size value and a negative value may be returned.
File file = new File("c:/temp/demo.txt");
long bytes = FileUtils.sizeOf(file);
4. Displaying Formatted Output of File Size
To display the size in a formatted manner to the end user, we may do the formatting ourselves or we can use the FileUtils.byteCountToDisplaySize()
method.
4.1. Custom Formatting
Use the String.format()
method to produce the formatted output strings as per requirements.
System.out.println(String.format("%,d Bytes", bytes));
System.out.println(String.format("%,d KB", bytes / 1024));
4.2. Using FileUtils.byteCountToDisplaySize()
The byteCountToDisplaySize() returns a human-readable version of the file size. Note that file size is rounded to the near KB, MB or GB.
System.out.println(FileUtils.byteCountToDisplaySize(2333444l)); //2 MB
System.out.println(FileUtils.byteCountToDisplaySize(2333444555l)); //2 GB
5. Conclusion
In this short tutorial, we learned to calculate the size of a file or directory in Java. We also saw how to format the file size for displaying to the user.
For regular files, we can use the Java IO classes. For calculating the size of directories, using Commons IO’s FileUtils
is an excellent choice.
Happy Learning !!
Comments