Java File Sorting Algorithm (file size, file name, file creation date)

Source: Internet
Author: User

Java file size, name, and date sorting method

// Sort by file size
public static void orderByLength(String fliePath) {List<File> files = Arrays.asList(new File(fliePath).listFiles());Collections.sort(files, new Comparator<File>() {public int compare(File f1, File f2) {long diff = f1.length() - f2.length();if (diff > 0)return 1;else if (diff == 0)return 0;elsereturn -1;}public boolean equals(Object obj) {return true;}});for (File f : files) {System.out.println(f.length());}}
// Sort by file name
public static void orderByName(String fliePath) {List<File> files = Arrays.asList(new File(fliePath).listFiles());Collections.sort(files, new Comparator<File>() {@Overridepublic int compare(File o1, File o2) {if (o1.isDirectory() && o2.isFile())return -1;if (o1.isFile() && o2.isDirectory())return 1;return o1.getName().compareTo(o2.getName());}});for (File f : files) {System.out.println(f.getName());}}
// Sort by file date
public static void orderByDate(String fliePath) {File file = new File(fliePath);File[] fs = file.listFiles();Arrays.sort(fs,new Comparator<File>(){public int compare(File f1, File f2) {long diff = f1.lastModified() - f2.lastModified();if (diff > 0)return 1;else if (diff == 0)return 0;elsereturn -1;}public boolean equals(Object obj) {return true;}});for (int i = fs.length-1; i >-1; i--) {System.out.println(fs[i].getName());System.out.println(new Date(fs[i].lastModified()).toLocaleString());}}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.