Filter a directory listing by dateTag(s): IO


This HowTo filters a directory listing based on a date interval.
import java.io.*;
import java.text.*;
import java.util.*;

public class FileFilterDateIntervalUtils implements FilenameFilter {
    String dateStart;
    String dateEnd;
    SimpleDateFormat sdf;

    public FileFilterDateIntervalUtils(String dateStart, String dateEnd) {
        this.dateStart = dateStart;
        this.dateEnd = dateEnd;
        sdf = new SimpleDateFormat("yyyy-MM-dd");
    }

    public boolean accept(File dir, String name) {
        Date d = new Date(new File(dir, name).lastModified());
        String current = sdf.format(d);
        return ((dateStart.compareTo(current) < 0 
                && (dateEnd.compareTo(current) >= 0)));
    }
}
Then
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        FileFilterDateIntervalUtils filter = 
            new FileFilterDateIntervalUtils("2004-01-01", "2004-12-31");
        File folder =  new File("C:/temp");
        File files[] = folder.listFiles(filter);
        for (File f : files) {
            System.out.println(f.getName() + " " 
                    + sdf.format(new Date(f.lastModified())));
        }
    }
}
Take a look at this HowTo to sort the filenames in ascending/descending order.
Take a look at this HowTo to sort the filenames based on the extension.

blog comments powered by Disqus