Apache FileUtils get file size

This example demonstrates how to get the file size using the Apache commons library.

Maven Dependency

Let's add maven dependency before creating these examples:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

Apache FileUtils get file size

In the example, we get the size of a file and a directory.


import java.io.File;
import org.apache.commons.io.FileUtils;

public class GetFileSizeEx {
    
    public static void main(String[] args) {
        
        File myfile = new File("/home/sourcecodeexamples/tmp/image.jpg");
        
        long fileSizeB = FileUtils.sizeOf(myfile);
        System.out.printf("The size of file is: %d bytes\n", fileSizeB);
        
        File mydir = new File("/home/janbodnar/tmp");
        
        long dirSizeB = FileUtils.sizeOfDirectory(mydir);
        double dirSizeKB = (double) dirSizeB / FileUtils.ONE_KB;
        double dirSizeMB = (double) dirSizeB / FileUtils.ONE_MB;
        
        System.out.printf("The size of directory is: %d bytes\n", dirSizeB);
        System.out.printf("The size of file is: %.2f kilobytes\n", dirSizeKB);
        System.out.printf("The size of file is: %.2f megabytes\n", dirSizeMB);        
    }
}

We determine the file size with FileUtils.sizeOf() and the directory size with FileUtils.sizeOfDirectory().

We used FileUtils.ONE_KB and FileUtils.ONE_MB constants to calculate the size in kilobytes and megabytes.

Comments