Delete Files with Java 8

A friend asked me to help him with the following in Bash – delete all files but a whitelisted and use mix / max depth for directory traversal. It’s probably possible in Bash with some crazy find, grep, etc one-liner.

But here’s how good it looks in Java 8 with streams, predicates, etc…

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class DeleteFiles {

	final static int MIN_DEPTH = 2;
	final static int MAX_DEPTH = 2;
	final static String ROOT_DIR = "/home/example";
	final static String WHITELISTED_FILE = "test.txt";

	public static <T> Predicate<T> not(Predicate<T> t) {
		return t.negate();
	}

	public static void main(String[] args) {
		try {
			try (Stream<Path> paths = Files.find(Paths.get(ROOT_DIR), MAX_DEPTH, (path, file) -> file.isRegularFile())
			        .filter(e -> e.getNameCount() - Paths.get(ROOT_DIR).getNameCount() >= MIN_DEPTH)
			        .filter(not(s -> s.toString().endsWith(File.separator + WHITELISTED_FILE)))) {
				
				paths.map(Path::toFile).forEach(
						file->{
						    System.out.println("To delete: " + file);
						    file.delete();
						});
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

With Java you can also easily extend the above functionality. Imagine the Bash hell you’ll get into when trying to whitelist a second file for example… Ahh, and it also works on Windows šŸ™‚

Comments

So empty here ... leave a comment!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Sidebar



%d bloggers like this: