Java - How to calculate directory (folder), file size

Here are various ways to get the size of a directory and file using the classes below in Java.

  • File
  • Files, Paths
  • Java8 Stream
  • Commons-io library

Let`s see with an example.

Calculate size with File class

File.length() returns the size of the file. The unit is bytes.

You can get the file size as follows, and you can also convert it to other units.

File file = new File("/home/js/test/myfile/file1.txt");
if (file.exists()) {
    double bytes = file.length();
    double kilobytes = (bytes / 1024);
    double megabytes = (kilobytes / 1024);
    double gigabytes = (megabytes / 1024);

    System.out.println("bytes : " + bytes);
    System.out.println("kilobytes : " + kilobytes);
    System.out.println("megabytes : " + megabytes);
    System.out.println("gigabytes : " + gigabytes);
} else {
    System.out.println("File does not exists!");
}

result

bytes : 169439.0
kilobytes : 165.4677734375
megabytes : 0.1615896224975586
gigabytes : 1.5780236572027206E-4
terabytes : 1.541038727737032E-7

However, if the above code is applied to Folder, it returns only 4096 bytes, which is the file size for Folder.

If the code below is executed, the file sizes under the /home/js/test/myfile folder are not calculated and only 4096 bytes are returned.

System.out.println();
File folder = new File("/home/js/test/myfile");
double bytes = folder.length();
System.out.println("bytes : " + bytes);
// output:
// bytes : 4096.0

If you want to calculate the size of all sub-files as well, you need to search all the sub-files and find the sum of the sizes of the files as follows.

File folder = new File("/home/js/test/myfile");
long bytes = getFolderSize(folder);
System.out.println("bytes : " + bytes);


public static long getFolderSize(File folder) {
    long length = 0;
    File[] files = folder.listFiles();
    int count = files.length;
    for (int i = 0; i < count; i++) {
        if (files[i].isFile()) {
            length += files[i].length();
        } else {
            length += getFolderSize(files[i]);
        }
    }
    return length;
}

The above code is implemented to search the file recursively. (recursive)

result

bytes : 7119049

Calculate file size using Files

You can browse the directory using Files in Java7. As you browse, if it`s a file and not a folder, just add up its size.

The following code is an example of calculating the size of the myfile folder.

Path folder = Paths.get("/home/js/test/myfile");
AtomicLong bytes = new AtomicLong(0);
try {
    Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            bytes.addAndGet(attrs.size());
            return FileVisitResult.CONTINUE;
        }
    });
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println("bytes : " + bytes);

result

bytes : 7119049

Calculate file size using stream

The Files class provides a Files.walk() method. This method creates a Stream subfile for the folder passed as an argument. ` Returns the type.

You can get the sum of the file sizes by filtering only the files in the Stream as follows:

Path folder = Paths.get("/home/js/test/myfile");
try {
    long bytes = Files.walk(folder)
            .filter(p -> p.toFile().isFile())
            .mapToLong(p -> p.toFile().length())
            .sum();
    System.out.println("bytes : " + bytes);
} catch (IOException e) {
    e.printStackTrace();
}

result

bytes : 7119049

Calculate file size using Commons-io

You can get the size of a directory more simply by using the Commons-io library.

To use Commons-io, in the case of a Gradle project, add the following to dependencies of build.gradle.

dependencies {
  compile group: 'commons-io', name: 'commons-io', version: '2.6'
  ...
}

For projects that use other build systems such as Maven, refer to mvnrepository.com and configure it.

Here is the code to calculate the file size in a directory.

File folder = new File("/home/js/test/myfile");
long bytes = FileUtils.sizeOfDirectory(folder);
System.out.println("bytes : " + bytes);

Returns the file size of the directory passed as an argument to FileUtils.sizeOfDirectory() in bytes.

result

bytes : 7119049

Reference

codechachaCopyright ©2019 codechacha