Elad Benda2
Elad Benda2

Reputation: 15472

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

I want to write code with a method that get a file path and a file name prefix

and delete all files in that dir path with that file name prefix except for the 10 newest files.

I wanted to use lambda (java 8)

but I'm not sure how ti filter 10 most recent files:

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

Upvotes: 2

Views: 2125

Answers (3)

SubOptimal
SubOptimal

Reputation: 22963

Please find a full working example which

  • create thirdy dummy files with different last modified timestamp
  • create a list of those files
  • shuffle them to show that the comparator is working as expected
  • delete or show the files, except the ten files with to most recent last modified timestamp

.

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

Upvotes: 5

laune
laune

Reputation: 31290

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

Upvotes: 1

ema
ema

Reputation: 951

Try using limit(10); after sorting in correct way

Another way is to use skip(10) and forEach( f--> removefile(f) ). I think it better fits.

Upvotes: 0

Related Questions