Home > Java, Java 1.6 Tutorial > Sorting directories and files in Java

Sorting directories and files in Java


We moved. Please visit this link for this post.

 

 

 

Several days ago we modified looks of our file manager in Wallpaper Changer application. In first version we used simple sort without Comparator or Comparable interfaces.

And finally I fixed this issue. I want to show how I did it. I used Comparator interface and Collator class.

class FileComparator implements Comparator {

private Collator collator = 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 collator.compare(f1.getName(), f2.getName());

}

}

Why I used Collator class. Collator class is useful when need compare locale-sensitive strings.  Also I used Comparator interface. It was useful for me. I passed its instance to the Arrays.sort(); method.

Also I want to show full example:

import java.io.File;

import java.text.Collator;

import java.util.Arrays;

import java.util.Comparator;

/**

* Class which represents how to sort correct dirs and files

* @author FaYna Soft Labs

*/

public class Main {

public static void main(String[] args) {

File directory = new File("C:/WINDOWS");

File[] filesArray = directory.listFiles();

if (filesArray != null) {

for (int i = 0; i < filesArray.length; i++) {

System.out.println(filesArray[i]);

}

System.out.println("###########################");

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

for (int i = 0; i < filesArray.length; i++) {

System.out.println(filesArray[i]);

}

}

}

private static class FileComparator implements Comparator {

private Collator collator = 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 collator.compare(f1.getName(), f2.getName());

}

}

}

As you can see sorting procedure is simple.

What do you think about? Leave a comment.

Advertisements
Categories: Java, Java 1.6 Tutorial
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: