Saturday, October 8, 2011

Java program to fetch and sort files from a directory

Hi - Have you worked with Java file system objects? It has very good features like accessing files and sorting them in ascending order and descending order. In Java 1.5, Sun Microsystem has introduced the Comparator class to make the sort operations easier. So, I'm going to discuss about this today.

When you create a File object, it will just create a reference for the path that you've given for the constructor. You can invoke methods like exists() to find whether the file exists or isDirectory() to find whether this file represents a directory on the disk etc.

Here is the sample program to to access files and order them by ascending order based on name, last modified date, and size. It explains about file filter as well.

SortFiles.java
package filesdemo;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.Comparator;

/**
 * A demo class to show the file sorting techniques.
 * @author Santhosh Reddy Mandadi
 * @since 05-Mar-2010
 * @version 1.0
 */
public class SortFiles
{
  public static void main(String[] args)
  {
    File dir = new File("C:\\");
    if(dir.isDirectory())
    {
      // Fetching the list from the directory
      File[] files = dir.listFiles();

      //Prints all the files and folders exists under dir
      for(File file:files)
      {
        System.out.println(file.getName());
      }
      System.out.println("All the files including folders");
      System.out.println("--------------------------------");
      
      // Creating a filter to return only files.
      FileFilter fileFilter = new FileFilter()
      {
        @Override
        public boolean accept(File file) {
          return !file.isDirectory();
        }
      };
      files = dir.listFiles(fileFilter);

      //Lists only files since we've applied file filter
      for(File file:files)
      {
        System.out.println(file.getName());
      }
      System.out.println("After filtering the folders");
      System.out.println("--------------------------------");

      // Sort files by name
      Arrays.sort(files, new Comparator()
      {
        @Override
        public int compare(Object f1, Object f2) {
          return ((File) f1).getName().compareTo(((File) f2).getName());
        }
      });

      //Prints the files in file name ascending order
      for(File file:files)
      {
        System.out.println(file.getName());
      }
      System.out.println("After sorting by name");
      System.out.println("----------------------------------");

      // Sort files by size.
      Arrays.sort(files, new Comparator()
      {
        @Override
        public int compare(Object f1, Object f2)
        {
          if (((File) f1).length() < ((File) f2).length())
          {
            return -1;
          }
          else if (((File) f1).length() > ((File) f2).length())
          {
            return 1;
          }
          else
          {
            return 0;
          }
        }
      });

      //Prints files in order by file size
      for(File file:files)
      {
        System.out.println(file.getName());
      }
      System.out.println("After sorting by length");
      System.out.println("-------------------------------");

      // Sort files by date.
      Arrays.sort(files, new Comparator()
      {
        @Override
        public int compare(Object f1, Object f2)
        {
          if (((File) f1).lastModified() < ((File) f2).lastModified())
          {
            return -1;
          }
          else if (((File) f1).lastModified() > ((File) f2).lastModified())
          {
            return 1;
          }
          else
          {
            return 0;
          }
        }
      });

      //Prints files in order by last modified date
      for(File file:files)
      {
        System.out.println(file.getName());
      }
      System.out.println("-------------------------");
    }
  }
}


Above program has been tested in 1.5 and 1.6.

Click here to check out other programs that I've developed.

0 comments:

Post a Comment