i'm trying to copy and paste 12 last modified files from a folder to another one.

my code is working but it gets every files in the folder with any dates.

any help will be appreciated.

Thank you very much

import java.io.*;
import java.text.*;
import java.util.*;

 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 hh:mm:ss a");

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)));

class FileSortDateInterval
    public static void main(String[] args)
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
    FileFilterDateIntervalUtils filter = new FileFilterDateIntervalUtils("2000-01-17 11:30:00 AM", "3011-12-31 10:30:00 PM");
    File folder = new File("C:/Files");
    File files[] = folder.listFiles(filter);
    for (File f : files) {
        System.out.println(f.getName() + " " + sdf.format(new Date(f.lastModified())));
        File dir = new File("C:/Last12Files");
        boolean success = f.renameTo(new File(dir,f.getName()));
        if (!success)


Well what I see from code you are just simply asking for array of all files i the folder and then print their name with time stamp.
What I do not see is:

  • some sort of collection where at least file name with it time stamp is stored
  • any attempt to sort by time stamp
  • any attempt to print/move/copy "ONLY" last 12 modified files

Thank you for your reply,
in fact this code is working very well , it selects and moves the 12 recent files because in the folder we have 12 files every day, so it selects only 12 recent files as i wanted in the beginning.

What i don't understand is this code is working at home but it doesn't at work.
I will check tomorrow may be i don't use the same folder with the same number of file
i will comeback.
But thank you