您要的是数字排序。您需要实现一个Comparator并将其传递给Arrays#sort方法。在compare方法中,您需要从每个文件名中提取数字,然后比较数字。
之所以得到现在得到的输出,是因为排序按字母数字顺序进行
这是一种非常基本的方法。此代码使用简单的
String*** 作来提取数字。如果您知道文件名的格式,则此方法有效
Spectrum_<number>.txt。一种更好的提取方法是使用正则表达式。
public class FileNameNumericSort { private final static File[] files = { new File("Spectrum_1.txt"), new File("Spectrum_14.txt"), new File("Spectrum_2.txt"), new File("Spectrum_7.txt"), new File("Spectrum_1000.txt"), new File("Spectrum_999.txt"), new File("Spectrum_9990.txt"), new File("Spectrum_9991.txt"), }; @Test public void sortByNumber() { Arrays.sort(files, new Comparator<File>() { @Override public int compare(File o1, File o2) { int n1 = extractNumber(o1.getName()); int n2 = extractNumber(o2.getName()); return n1 - n2; } private int extractNumber(String name) { int i = 0; try { int s = name.indexOf('_')+1; int e = name.lastIndexOf('.'); String number = name.substring(s, e); i = Integer.parseInt(number); } catch(Exception e) { i = 0; // if filename does not match the format // then default to 0 } return i; } }); for(File f : files) { System.out.println(f.getName()); } }}
输出量
Spectrum_1.txtSpectrum_2.txtSpectrum_7.txtSpectrum_14.txtSpectrum_999.txtSpectrum_1000.txtSpectrum_9990.txtSpectrum_9991.txt
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)