按照在应用程序中显示之前创建的日期对文件进行排序

时间:2015-03-01 09:19:06

标签: java android

如何按照在我自己的应用中的列表视图中显示之前创建的日期对文件进行排序?

我使用了files.lastModified(),我不想使用它,因为重命名会混淆它。无论如何我可以通过创建日期来对其进行排序吗?我也尝试将文件名映射到时间和日期,但这太乏味了。

1 个答案:

答案 0 :(得分:0)

由于您使用Java 7,因此可以使用属性API来获取所需内容。

不幸的是,访问创建时间要求您读取可能导致IOException的属性,因此您必须处理...

示例代码:

private static FileTime getCreationTime(final Path path)
{
    final BasicFileAttributes attrs;
    try {
        attrs = Files.readAttributes(path, BasicFileAttributes.class);
        return attrs.creationTime();
    } catch (IOException oops) {
        throw new RuntimeException("can't read attributes from " + path, oops);
    }
}

private static final Comparator<Path> CREATION_TIME_COMPARATOR
    = new Comparator<Path>()
    {
        @Override
        public int compare(final Path o1, final Path o2)
        {
            return getCreationTime(o1).compareTo(getCreationTime(o2));
        }
    };

现在,使用Files.newDirectoryStream()将文件条目读入列表:

final Path baseDir = Paths.get("whever");

final List<Path> entries = new ArrayList<>();

for (final Path entry: Files.newDirectoryStream(baseDir))
    entries.add(entry);

Collections.sort(entries, CREATION_TIME_COMPARATOR);
相关问题