Sort files by the extension

From CodeCodex

Revision as of 07:38, 25 July 2010 by 211.2.129.92 (Talk)

Implementations

Java

<highlightsyntax language="java122"> import java.io.*; import java.util.Arrays; import java.util.ArrayList; import java.util.List; import java.util.Comparator;

public class FileUtils{

 /**
  * returns a folder content sorted by extension
  * case-insensitive ,ascending order
  * subfolders are not included
  * @param folder  folder name
  * @return  
  * @throws IOException  if not a folder or not found
  */
 @SuppressWarnings("unchecked")
 public static File[] dirListByExtension(File folder) throws IOException {
   if (!folder.isDirectory() || !folder.exists()) {
     throw new IOException( folder.getName() + " : Not a folder or not exist");
   }
   File files[] = FileUtils.list(folder, false); // don't include subfolder
   Arrays.sort(files, new Comparator() {
     public int compare(final Object o1, final Object o2) {
         String s1 = ((File) o1).getName().toLowerCase();
         String s2 = ((File) o2).getName().toLowerCase();
         final int s1Dot = s1.lastIndexOf('.');
         final int s2Dot = s2.lastIndexOf('.');
         // 
         if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither
             s1 = s1.substring(s1Dot + 1);
             s2 = s2.substring(s2Dot + 1);
             return s1.compareTo(s2);
         } else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first
             return -1;
         } else { // only s1 has an extension, so s1 goes second
             return 1;
         }
     }
   });
  return files;
 }  
 
 /**
  * returns the content of a folder with subfolders included or not
  * @param folder   folder name
  * @param includeSubFolder  true/false
  * @return  array of files
  */
 public static File[] list(File folder, boolean includeSubFolder) {
   if (!folder.isDirectory()) {
     return null;
   }
   File files[] = folder.listFiles();
   List<File> list = new ArrayList<File>();
   for (File file : files) {
     if (file.isDirectory()) {
       if (includeSubFolder) {
         list.add(file);  
       }
     }
     else {
      list.add(file);
     }
   }
   if (list.isEmpty()) {
     return null;
   }
   return list.toArray(new File[]{});
 }
 /*
  * TEST
  */
 public static void main(String args[]) throws Exception {
   File files[] = FileUtils.dirListByExtension(new File("C:/temp"));
   for (File file : files) {
     System.out.println(file.getName());
   }
   // to reverse
   //   List<File> temp = Arrays.asList(files);
   //   java.util.Collections.reverse(temp);
   //   files = temp.toArray(new File[]{});
   //   for (File file : files) {
   ///     System.out.println(file.getName());
   //   }
 
 }

} </highlightsyntax> Take a look at this HowTo to filter by a date interval. Take a look at this HowTo to sort the filenames in ascending/descending order (based on the last modified timestamp).

Ruby

def dirlist_by_extension(dirname)
  Dir.chdir(dirname) do |dir|
    files = Dir.entries('.')
    i = 0
    files.sort_by{|fname| [File.extname(fname).downcase, i+=1]}
  end
end

files = dirlist_by_extension('/')
files.each do |file|
  puts file
end