I\'m able to do this:
File images = new File(path);
File[] imageList = images.listFiles(new FilenameFilter(){
public boolean accept(File
final File[] sortedFileName = images.listFiles()
if (sortedFileName != null && sortedFileName.length > 1) {
Arrays.sort(sortedFileName, new Comparator<File>() {
@Override
public int compare(File object1, File object2) {
return object1.getName().compareTo(object2.getName());
}
});
}
Use Array.sort()
to compare the name of the files.
Edit: Use this code to sort by date
final File[] sortedByDate = folder.listFiles();
if (sortedByDate != null && sortedByDate.length > 1) {
Arrays.sort(sortedByDate, new Comparator<File>() {
@Override
public int compare(File object1, File object2) {
return (int) ((object1.lastModified() > object2.lastModified()) ? object1.lastModified(): object2.lastModified());
}
});
}
I was getting an exception
IllegalArgumentException: Comparison method violates its general contract!
so I used this and it worked ok:
Arrays.sort(filesList, new Comparator<File>() {
@Override
public int compare(File a, File b) {
if(a.lastModified() < b.lastModified() )
return 1;
if(a.lastModified() > b.lastModified() )
return -1;
return 0;
}});
If you want to sort date wise then choose below code, and if you want name then already answer is above :)
File f = new File("/home/myfiles");
File [] files = f.listFiles();
Arrays.sort( files, new Comparator(){
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
return +1;
} else {
return 0;
}
}
});
you can use below code. worked for me.
final File[] files= file.listFiles();
if (files != null && files.length > 1) {
Collections.sort(Arrays.asList(files), new Comparator<File>() {
public int compare(File o1, File o2) {
long lastModifiedO1 = o1.lastModified();
long lastModifiedO2 = o2.lastModified();
return (lastModifiedO2 < lastModifiedO1) ? -1 : ((lastModifiedO1 > lastModifiedO2) ? 1 : 0);
}
});
}
Pointers :
File.isDirectory()
File.lastModified()
I solved this problem by using this
final File[] sortedByDate = folder.listFiles();
if (sortedByDate != null && sortedByDate.length > 1) {
Arrays.sort(sortedByDate, new Comparator<File>() {
@Override
public int compare(File object1, File object2) {
return (int) ((object1.lastModified() > object2.lastModified()) ? 0: 1);
}
});
}
I return 0 and 1 insted of lastModified()
value that solved my problem.