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

Ela*_*da2 2 java lambda file filter

我想用获取 afile path和 a的方法编写代码file name prefix

并删除dir path其中file 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;
                    }
                });
    }
Run Code Online (Sandbox Code Playgroud)

Sub*_*mal 5

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

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

.

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)