Skip to content

Java file size with FileUtils.sizeOf()

Ramesh Fadatare edited this page Jul 12, 2019 · 1 revision

In this example, we determine the file size with Apache Commons' FileUtils. Its method for finding out the file size is sizeOf().

For this example, we need the commons-io dependency:

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

Java file size with FileUtils.sizeOf()

The code example determines the file size using Apache Commons' FileUtils' sizeOf() method.

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

public class JavaFileSizeExample {

    public static void main(String[] args) throws IOException {

        String fileName = "src/main/resources/words.txt";
        File f = new File(fileName);

        long fileSize = FileUtils.sizeOf(f);        

        System.out.format("The size of the file: %d bytes", fileSize);
    }
}

Output:

The size of the file: 200 bytes
Clone this wiki locally