Reputation: 5451
I am trying to read the latest 10 files based on their creation date .
I tried with this code , but it isn't working , i mean , it doesn't show the new file names in the output when ever i add new files .
import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
File inboxDir = new File("D:\\SPOTO");
File[] files = inboxDir.listFiles();
Arrays.sort( files, new Comparator()
{
public int compare(Object o1, Object o2) {
return new Long(((File)o1).lastModified()).compareTo(new Long(((File) o2).lastModified()));
}
});
for(int i=0;i<10;i++)
{
System.out.println(files[i].getName());
}
}
}
I even tried with apache commons io , but that isn't working either ( Means doesn't show new files when new files are created in that directory )
This is my Apache commons io version
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import java.io.File;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
File dir = new File("c:\\");
File[] files = dir.listFiles();
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
for (int i = 0; i < files.length; i++) {
File file = files[i];
System.out.printf("File %s - %2$tm %2$te,%2$tY%n= ", file.getName(),
file.lastModified());
}
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
for (int i = 0; i < files.length; i++) {
File file = files[i];
System.out.printf("File %s - %2$tm %2$te,%2$tY%n= ", file.getName(),
file.lastModified());
}
}
}
Upvotes: 2
Views: 10848
Reputation: 1314
Try flipping the comparison order:
return new Long(((File)o2).lastModified()).compareTo(new Long(((File) o1).lastModified()));
This works for me testing locally just now.
Upvotes: 3
Reputation: 24722
At least in regular Java version you compare files in the wrong (ascending) order. I multiplied result by -1 and I am seeing latest files first:
return -1* (new Long(((File)o1).lastModified()).compareTo(new Long(((File) o2).lastModified())));
With timestamps the larger one corresponds to the newer file.
Upvotes: 2