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());
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…