DirectoryStream.Filter示例,用于列出基于特定日期/时间的文件 [英] DirectoryStream.Filter example for listing files that based on certain date/time

查看:57
本文介绍了DirectoryStream.Filter示例,用于列出基于特定日期/时间的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试研究 newDirectoryStream DirecoryStream.Filter 示例,在此示例中,我可以列出目录(及其所有子目录)(例如,超过60天).

I am trying to investigate a DirecoryStream.Filter example for newDirectoryStream where I can achieve to list all files under a directory(and all its sub directories) that are older than 60 days, as an example.

DirectoryStream<Path> dirS = Files.newDirectoryStream(Paths.get("C:/myRootDirectory"), <DirectoryStream.filter>);

for (Path entry: dirS) {
    System.out.println(entry.toString());
}

在上面的代码中, DirectoryStream.filter 应该是什么?
这对我有很大的帮助,因为我在一个项目中尝试删除早于某个时间戳的文件,并且Java 1.7之前的版本 File.listFiles()挂起.

In the code above, what should be the DirectoryStream.filter?
It will be a great help as I am in a project where I am trying to delete files older than a certain timestamp and pre-java 1.7 File.listFiles() just hangs.

Files.walkFileTree()是否可以提供选项?

推荐答案

如果我理解正确,则有两种情况:

If I get this right, you have 2 situations:

  1. 创建自定义过滤器以选择60天以上的文件
  2. 遍历子目录(整个 FileTree )并收集您的信息
  1. Create a custom filter to select files older than 60 days
  2. Traverse through subdirectories (the entire FileTree) and gather your information

使用 Calendar 类实施60天的条件后,自定义过滤器更易于实现:

The custom filter is easier to implement with conditions of 60 days implemented using Calendar class:

DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
    @Override
    public boolean accept(Path entry) throws IOException {BasicFileAttributes attr = Files.readAttributes(entry,BasicFileAttributes.class);
    FileTime creationTime = attr.creationTime();
    Calendar cal = Calendar.getInstance();
    int days = cal.fieldDifference(new Date(creationTime.toMillis()),Calendar.DAY_OF_YEAR);
        return (Math.abs(days) > 60);
        }
  };

正常执行将仅在根目录中查找文件.要查找子目录,使用 walkFileTree()的猜测是正确的.

The normal execution would only look for the files in the root directory. To look for subdirectory, your guess of using walkFileTree() is right.

但是,这需要实现 FileVisitor 接口,该接口的简单实现幸运地与7- SimpleFileVisitor 捆绑在一起.

However, this requires an implementation of the FileVisitor interface, a simple implementation of which luckily is bundled with 7 - SimpleFileVisitor.

要遍历子目录,可以选择覆盖特定于目录的方法-我在这里使用了 SimpleFileVisitor preVisitDirectory :

To traverse through the subdirectories, you can choose to override a directory specific method - I have used preVisitDirectory of SimpleFileVisitor here:

Files.walkFileTree(dirs, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path file,
                    BasicFileAttributes attrs) {

由于 preVisitDirectory 将被定制为返回FileVisitResult.CONTINUE; ,如果您没有任何其他限制,我们将利用 preVisitDirectory 方法,同时应用过滤器,一次遍历目录1.

Since preVisitDirectory will be custom made to return FileVisitResult.CONTINUE; in case you don't have any additional restrictions, we would leverage preVisitDirectory method to iterate through our directory 1 at a time while applying the filter.

Files.walkFileTree(dirs, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path file,
                    BasicFileAttributes attrs) {

                DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
                    @Override
                    public boolean accept(Path entry) throws IOException {
                        BasicFileAttributes attr = Files.readAttributes(entry,
                                BasicFileAttributes.class);
                        FileTime creationTime = attr.creationTime();
                        Calendar cal = Calendar.getInstance();
                        int days = cal.fieldDifference(
                                new Date(creationTime.toMillis()),
                                Calendar.DAY_OF_YEAR);
                        return (Math.abs(days) > 60);
                    }
                };
                try (DirectoryStream<Path> stream = Files.newDirectoryStream(
                        file, filter)) {
                    for (Path path : stream) {
                        System.out.println(path.toString());
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                return FileVisitResult.CONTINUE;

            }
        }); 

这将为您提供整个目录和子目录结构中的文件,以提供所需的过滤条件,并在下面完成主要方法:

This would give you the files from the entire directory and subdirectory structures for the required filter criteria, complete main method below:

public static void main(String[] args) throws IOException {
        Path dirs = Paths.get("C:/");

        Files.walkFileTree(dirs, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path file,
                    BasicFileAttributes attrs) {

                DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
                    @Override
                    public boolean accept(Path entry) throws IOException {
                        BasicFileAttributes attr = Files.readAttributes(entry,
                                BasicFileAttributes.class);
                        FileTime creationTime = attr.creationTime();
                        Calendar cal = Calendar.getInstance();
                        int days = cal.fieldDifference(
                                new Date(creationTime.toMillis()),
                                Calendar.DAY_OF_YEAR);
                        return (Math.abs(days) > 60);
                    }
                };
                try (DirectoryStream<Path> stream = Files.newDirectoryStream(
                        file, filter)) {
                    for (Path path : stream) {
                        System.out.println(path.toString());
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                return FileVisitResult.CONTINUE;

            }
        });

    }

这篇关于DirectoryStream.Filter示例,用于列出基于特定日期/时间的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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