I need to sort an array of files by the date which is part of the name of the file e.g.: "20200611_2130.dat"
.
I tried doing it with:
Arrays.sort(files,new FileNameComparator());
public class FileNameComparator implements Comparator<File> {
private static SimpleDateFormat formatter =
new SimpleDateFormat("YYYYddMM_HHmm");
@Override
public int compare(File a, File b) {
try {
return asTime(a.getName()) > asTime(b.getName()) ? 1 : -1;
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
private static long asTime(String filename) throws ParseException {
return formatter.parse(
filename.substring(0, filename.lastIndexOf("."))).getTime();
}
}
I know there is a lot to fix here, but right now I would like to understand why I get:
"Comparison method violates its general contract!"