Frage

I'm just trying to figure out how I can sort a directory listing according to it's name, time last modified and size. I know you can access the file's name, size, last modified with the File methods but I'm not sure how to go about sorting it. If someone can point me in the right direction it would great.

public void printDirectoryContents(String path, PrintWriter writer)
{
    File[] list = root.listFiles();
    Arrays.sort(list);

    for ( File f : list )
    {           
        String name = f.getName();
        long lastmod = f.lastModified();
        SimpleDateFormat simple = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
        String formatted = simple.format(new Date(lastmod));
        long length = f.length();

    }
}
War es hilfreich?

Lösung

You should implement a Comparator to sort the files based on the attributes you mentioned, and pass this as an argument to the Arrays.sort method.

    Arrays.sort(list, new Comparator<File>()
    {
        public int compare(File file1, File file2)
        {
            int result = ...
            .... comparison logic
            return result;
        }
    });

Andere Tipps

Create a Comparator for each sorting needs. Then use that Comparator to sort the File objects in a particular Collection.

http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html

You can check for more examples here:

http://www.javadeveloper.co.in/java-example/java-comparator-example.html

You can write your own comparator

public class FileComparator implements Comparator<File> {

    //This should sort first by name then last-modified and then size
    public int compare(File f1, File f2) {
        int nameComparisonResult = o1.getName().compareTo(o2.getName());
        if(nameComparisonResult != 0) return nameComparisonResult;
        int lModCompResult = Long.valueOf(o1.lastModified()).compareTo(Long.valueOf(o2.lastModified()));
        if(lModCompResult != 0) return lModCompResult;      
        return Long.valueOf(o1.getTotalSpace()).compareTo(Long.valueOf(o2.getTotalSpace()));
    }
}

and use it to sort the array Arrays.sort(list, new FileComparator());.

Instead of Arrays.sort(list); consider using something like this:

    Arrays.sort(list, new Comparator<File>() {
        @Override
        public int compare(File file1, File file2) {
            //your comparison logic
            return <your_return_value>;
        }

    });

You can then go ahead and write your comparison logic based on filename, date and size in the compare(...) method

Take a look at Apache Commons IO.

You can find Comparators for all your requirements.

For usage, see there: http://commons.apache.org/io/api-release/org/apache/commons/io/comparator/package-summary.html#package_description

Sorting
 All the compartors include convenience utility sort(File...) and sort(List) methods. 

 For example, to sort the files in a directory by name: 
 File[] files = dir.listFiles();
 NameFileComparator.NAME_COMPARATOR.sort(files);

 ...alternatively you can do this in one line: 
 File[] files = NameFileComparator.NAME_COMPARATOR.sort(dir.listFiles());

Composite Comparator
 The CompositeFileComparator can be used to compare (and sort lists or arrays of files) by combining a number other comparators. 

This class will show you implementation of Comparable interface and sort a list according to file name using Collections.sort method.

package com.roka.tgpl.sms;



  import java.util.ArrayList;
  import java.util.Calendar;
  import java.util.Collections;

  import java.util.Date;
  import java.util.List;




  public class MyFile implements Comparable<MyFile> {

     private String name;
     private Date lastModified;
     private int size;

     MyFile(String name,Date lastModified,int size){
         this.name = name;
         this.lastModified =lastModified;
         this.size = size;
     }
     /**
    * @return the name
    */
    public String getName() {
       return name;
   }


   /**
    * @param name the name to set
    */
   public void setName(String name) {
       this.name = name;
   }


   /**
    * @return the lastModified
    */
   public Date getLastModified() {
    return lastModified;
   }


   /**
    * @param lastModified the lastModified to set
    */
   public void setLastModified(Date lastModified) {
       this.lastModified = lastModified;
   }


    /**
     * @return the size
    */
   public int getSize() {
        return size;
   }


   /**
    * @param size the size to set
    */
   public void setSize(int size) {
    this.size = size;
   }


   public int compareTo(MyFile o) {

         int compare = this.name.compareTo(o.getName());

       return compare;
    }



    public static void main(String arg []) {

       List<MyFile> fileList = new ArrayList<MyFile>();
       fileList.add(new MyFile("DCB", Calendar.getInstance().getTime(), 5));
       fileList.add(new MyFile("ABC", Calendar.getInstance().getTime(), 15));
        Collections.sort(fileList);

       for(MyFile file : fileList){
            System.out.println(file.getName());
           }

      }

    }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top