如何根据名称,大小和上次修改对目录列表进行排序?

时间:2012-10-26 17:22:00

标签: java file sorting directory directory-listing

我只想弄清楚如何根据它的名称,上次修改的时间和大小来对目录列表进行排序。我知道您可以访问文件的名称,大小,最后使用File方法修改但我不知道如何对其进行排序。如果有人能指出我正确的方向,那就太好了。

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();

    }
}

6 个答案:

答案 0 :(得分:3)

您应该实现Comparator根据您提到的属性对文件进行排序,并将其作为参数传递给Arrays.sort方法。

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

答案 1 :(得分:1)

为每个排序需求创建Comparator。然后使用Comparator对特定Collection中的File对象进行排序。

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

您可以在此处查看更多示例:

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

答案 2 :(得分:1)

您可以编写自己的比较器

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()));
    }
}

并使用它对数组Arrays.sort(list, new FileComparator());进行排序。

答案 3 :(得分:0)

而不是Arrays.sort(list);考虑使用类似的东西:

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

    });

然后您可以继续根据compare(...)方法中的文件名,日期和大小编写比较逻辑

答案 4 :(得分:0)

看看Apache Commons IO

您可以找到满足您所有要求的比较器。

有关用法,请参阅: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. 

答案 5 :(得分:0)

该类将向您展示Comparable接口的实现,并使用Collections.sort方法根据文件名对列表进行排序。

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());
           }

      }

    }