日期:2014-05-20 浏览次数:20918 次
package it.heber.sandbox;
import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
public class FileComperator2 {
private static File[] images;
public static void main(String[] args) {
File folder = new File("e:\\q");//1.txt,2.txt,3.txt 一共三个文件
images = folder.listFiles();
sortFilesByIdName(true);
}
/**
* Function sorts files by their Id on the end of the file name.
* (e.q. img_1.png, img_2.png, ...)
*
* @param sortAsc sorting Flag [true=ASC|false=DESC]
*/
public static void sortFilesByIdName(final boolean sortAsc) {
Comparator<File> comparator = new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
if (sortAsc) {
return getFileId(o1).compareTo(getFileId(o2));
} else {
return -1 * getFileId(o1).compareTo(getFileId(o2));
}
}
};
Arrays.sort(images, comparator);
System.out.println("###n### Sort file by Id in file name ######");
for (File image : images) {
System.out.println(image.getName() + "t" +
new Date(image.lastModified()));
}
}
/**
* Helper method to determine file Id for sorting. File name has following
* structure: img_11.png
*
* @param file
* @return
*/
private static Integer getFileId(File file) {
String fileName = first(file.getName().split("."));
String fileId = last(fileName.split("_"));
return Integer.parseInt(fileId);
}
/**
* Generic helper methode to get the last field of an array
*
* @param <T> Array type
* @param array Array with elements
* @return last field of an array
*/
private static <T> T last(T[] array) {