Hi,

is it possible to get the list of last life added in a folder with java?
i don't want to get the lastmodified file which return a date or time.
i want to get the file name of last added in a folder.
Thank you all

No, there isn't a build-in mechanism for that. You will need to get the list of files in the directory with list() or listFiles() and then check lastModified() on them to determine the most recent.

Edited 5 Years Ago by Ezzaral: n/a

OK, but here is a code that list the last modified files in a directory between two dates.
This is working well but is it possible to do the same thing between two times like
get the last modified file bet 02:00:00am and 01:00:00am (so the interval time is 23h)

Thanks

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 FileSortDateInterval {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        FileFilterDateIntervalUtils filter =
            new FileFilterDateIntervalUtils("2010-01-04", "2011-01-20");
        File folder =  new File("G:/Temp");
        File files[] = folder.listFiles(filter);
        for (File f : files) {
            System.out.println(f.getName() + " "
                    + sdf.format(new Date(f.lastModified())));
        }
    }
}

You could use the Date object itself to determine those hour ranges instead of converting the dates to strings for the comparison.

This article has been dead for over six months. Start a new discussion instead.