如何使用 java 将最后 10 个最新文件保留在目录中?

how can I leave only last 10 newest files in a dir using java?

我想用一个方法编写代码来获取 file pathfile name prefix

并删除 dir pathfile name prefix 中的所有文件,除了 10 个最新文件。

我想使用 lambda (java 8)

但我不确定如何过滤 10 个最近的文件:

   public Optional<File> getLatestFileFromDir(String baseLineFileName) {
        File baseLineFile = new File(baseLineFileName);
        File dir = baseLineFile.getParentFile();
        File[] files = dir.listFiles();

        if (files == null || files.length == 0) {
            return null;
        }
        return Arrays.asList(dir.listFiles()).stream()
                .filter(file -> isNameLikeBaseLine(file, baseLineFile.getName()))
                .max(new Comparator<File>() {
                    @Override
                    public int compare(File o1, File o2) {
                        int answer;
                        if (o1.lastModified() == o2.lastModified()) {
                            answer = 0;
                        } else if (o1.lastModified() > o2.lastModified()) {
                            answer = 1;
                        } else {
                            answer = -1;
                        }
                        return answer;
                    }
                });
    }

尝试使用限制(10);正确排序后

另一种方法是使用 skip(10) 和 forEach( f--> removefile(f) )。我觉得比较合适。

Arrays.asList(dir.listFiles()).stream()
            .filter(file -> isNameLikeBaseLine(file, baseLineFile.getName()))
            .sorted(new Comparator<File>() {
                @Override
                public int compare(File o1, File o2) {
                    int answer;
                    if (o1.lastModified() == o2.lastModified()) {
                        answer = 0;
                    } else if (o1.lastModified() > o2.lastModified()) {
                        answer = -1;
                    } else {
                        answer = 1;
                    }
                    return answer;
                }
            }).limit( 10 );

请找到一个完整的工作示例

  • 创建具有不同上次修改时间戳的第三个虚拟文件
  • 创建这些文件的列表
  • 打乱它们以表明比较器按预期工作
  • 删除或显示文件,但具有最近修改时间戳的十个文件除外

.

public class KeepTopTenFiles {

    public static void main(String[] args) throws IOException {
        ArrayList<File> files = new ArrayList<>();
        createDummyFiles(files);
        Collections.shuffle(files);

        files.stream()
                .filter((File p) -> p.getName().matches("foobar_.*"))
                .sorted(getReverseLastModifiedComparator())
                .skip(10)
                // to delete the file but keep the most recent ten
                // .forEach(x -> ((File) x).delete());
                // or display the filenames which would be deleted
                .forEach((x) -> System.out.printf("would be deleted: %s%n", x));
    }

    private static Comparator<File> getReverseLastModifiedComparator() {
        return (File o1, File o2) -> {
            if (o1.lastModified() < o2.lastModified()) {
                return 1;
            }
            if (o1.lastModified() > o2.lastModified()) {
                return -1;
            }
            return 0;
        };
    }

    private static void createDummyFiles(ArrayList<File> files) throws IOException {
        long timestamp = System.currentTimeMillis();
        int filesToCreate = 30;
        for (int i = 0; i < filesToCreate; i++) {
            long lastModified = timestamp + 5 * i;
            String fileName = String.format("foobar_%02d", i);
            File file = new File(fileName);
            file.createNewFile();
            file.setLastModified(lastModified);
            files.add(file);
        }
    }
}