标签:++ exce print array .so for lis rri i++
我们想要输出(1.jpg、2.jpg、3.jpg、10.jpg、11.jpg、20.jpg、21.jpg、31.jpg)
突然看到网上一些写法
总结:既然自己按照定义的文件名规则来处理,也可以进行使用正则表达,简化使用
1 File[] files = file.listFiles(); 2 if(files==null)return resultFileName; 3 List<File> fileList = new ArrayList<File>(); 4 for (File f : files) { 5 fileList.add(f); 6 } 7 8 Collections.sort(fileList, new Comparator<File>() { 9 @Override 10 public int compare(File o1, File o2) { 11 if (o1.isDirectory() && o2.isFile()) 12 return -1; 13 if (o1.isFile() && o2.isDirectory()) 14 return 1; 15 return o2.getName().compareTo(o1.getName()); 16 } 17 }); 18 19 for (File f : fileList) { 20 if(f.isDirectory()){ 21 resultFileName.add(f.getPath()); 22 ergodic(f,resultFileName); 23 }else 24 resultFileName.add(f.getPath()); 25 }
但是它输出的是:(1.jpg、10.jpg、11.jpg、2.jpg、20.jpg、21.jpg、3.jpg、31.jpg)
看到这个明显是按照字典顺序来排序的 既然我们想要按照Integer 大小来进行排序处理
1 public static void main(String[] args) throws IOException { 2 File file = new File(path); 3 File[] files = file.listFiles(); 4 ArrayList<File> list = new ArrayList<>(); 5 for (File file2 : files) { 6 7 list.add(file2); 8 } 9 10 Collections.sort(list, new Comparator<File>() { 11 @Override 12 public int compare(File o1, File o2) { 13 if (o1.isDirectory() && o2.isFile()) 14 return -1; 15 if (o1.isFile() && o2.isDirectory()) 16 return 1; 17 Integer f = f(o1.getName()); 18 Integer f2 = f(o2.getName()); 19 return Integer.compare(f, f2); 20 } 21 }); 22 for (File file2 : list) { 23 System.out.println(file2.getName()); 24 } 25 26 } 27 28 static Integer f(String filename) { 29 int x = filename.indexOf("."); 30 String string2 = filename.substring(0,x); 31 char[] cs = string2.toCharArray(); 32 StringBuilder builder = new StringBuilder(); 33 for (int i = 0; i < cs.length; i++) { 34 if(Character.isDigit(cs[i])) { 35 builder.append(cs[i]); 36 } 37 } 38 return Integer.parseInt(builder.toString()); 39 }
使用正则表达式
1 public final class FileString implements Comparable<FileString> { 2 private final String fileName; 3 private final int prefix_num; 4 Pattern number = Pattern.compile("(\\d+)\\..*"); 5 6 public FileString(String fileName) { 7 this.fileName = fileName; 8 Matcher matcher = number.matcher(fileName); 9 if (matcher.find()) { 10 prefix_num = Integer.parseInt(matcher.group(1)); 11 } else { 12 prefix_num = 0; 13 } 14 } 15 16 @Override 17 public int compareTo(FileString o) { 18 return o.prefix_num > prefix_num ? -1 : o.prefix_num == prefix_num ? 0 : 1; 19 } 20 21 @Override 22 public String toString() { 23 return fileName; 24 } 25 }
标签:++ exce print array .so for lis rri i++
原文地址:https://www.cnblogs.com/dgwblog/p/9222144.html