Clean up a directory Tag(s): IO


Delete all files and subdirectories (content and structure).
import java.io.File;

public class CleanUpDirectoryDemo {
   public static void main(String[] args) {
      CleanUpDirectoryDemo.cleanupDirectory(new File("c:/temp/foo"));
   }

   public static void cleanupDirectory(File dir) {
      for (File file: dir.listFiles()) {
          if (file.isDirectory())
              cleanupDirectory(file);
          file.delete();
      }
   }
}
Java 8: Delete all files (not subdirectories)
import java.nio.file.Files;
import java.util.Arrays;
...

Arrays.stream(new File(context.workdir).listFiles()).forEach(File::delete);
Java 8: Delete all files and subdirectories content (keep the structure)
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;

public class CleanUpDirectoryDemo {
   public static void main(String[] args) throws IOException {
      CleanUpDirectoryDemo.cleanupDirectory(Paths.get("c:/temp/foo"));
   }

   public static void cleanupDirectory(Path dir) throws IOException {
      Files.walk(dir)
      .filter(Files::isRegularFile)
      .map(Path::toFile)
      .forEach(File::delete);
  }
}



comment Comments