The Wannabe Java Rockstar: How to Sort Files and Directories

How to Sort Files and Directories

Via Technorati's new tag feature I found a quick and dirty algorithm for sorting files and directories. The author asked for improved versions. Here's mine:

import java.io.File;
import java.text.Collator;
import java.util.Arrays;
import java.util.Comparator;

public class FileSort
{
public static void main(String[] args)
{
 
File dir = new File("D:/home/schwarz/Eigene Dateien");
  File
[] selectedFiles = dir.listFiles();

 
if(selectedFiles != null)
    {
     
for(int i = 0; i < selectedFiles.length; i++)
       
System.err.println(selectedFiles[i]);

      Arrays.sort
(selectedFiles, new FileComparator());

     
for(int i = 0; i < selectedFiles.length; i++)
       
System.err.println(selectedFiles[i]);
   
}
}

private static class FileComparator
 
implements Comparator
{
private Collator c = Collator.getInstance();

public int compare(Object o1,
                   Object o2
)
{
 
if(o1 == o2)
   
return 0;

  File f1 =
(File) o1;
  File f2 =
(File) o2;

 
if(f1.isDirectory() && f2.isFile())
   
return -1;
 
if(f1.isFile() && f2.isDirectory())
   
return 1;

 
return c.compare(f1.getName(), f2.getName());
}
}
}


Update:

I was a bit lazy with error handling. Usually, I'm totally not like that ;-). Thank you, Peter, for reminding me in the comments that listFiles() can return a null value.

Sun, 16 Jan 2005, 23:15 | Java | PermaLink
« Company Names That Should Be Forbidden | Home | Another Happy CityDesk Blogger »