Java SizeFileFilter-class And Method Code Example


Here is an example of how to use the SizeFileFilter class from the Apache Commons IO library to filter files based on their size:

import org.apache.commons.io.filefilter.SizeFileFilter;

import java.io.File;
import java.io.FileFilter;

public class Main {
    public static void main(String[] args) {
        // Minimum file size
        long minSize = 10; 
        // Maximum file size
        long maxSize = 100; 

        // Creating a FileFilter
        FileFilter sizeFilter = new SizeFileFilter(minSize, maxSize);
        File dir = new File("/path/to/directory");

        // Retrieving files that match the filter
        File[] files = dir.listFiles(sizeFilter);

        for (File file : files) {
            System.out.println(file.getName());
        }
    }
}

In this example, the SizeFileFilter is used to filter files in a directory based on their size. The filter is created with a minimum file size of 10 bytes and a maximum file size of 100 bytes. The listFiles method is then used to retrieve all files in the directory that match the filter. The names of the filtered files are then printed to the console.