如何根据名称,大小和最后修改对目录列表进行排序? [英] How can I sort a directory listing according to name, size and last modified?

查看:249
本文介绍了如何根据名称,大小和最后修改对目录列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想弄清楚我可以根据它的名称,上次修改的时间和大小来排序目录列表​​。我知道你可以访问文件的名称,大小,最后修改与文件方法,但我不知道如何去排序。如果有人能指出我正确的方向,那会很棒。

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

    }
}


推荐答案

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

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

这篇关于如何根据名称,大小和最后修改对目录列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆