Wednesday, 29 April 2020

Delete all the files in a directory

Write a program to delete all the files in a directory recursively (Not the directories).

Input Directory structure
1
├── 2
│   ├── 2.1
│   │   └── b.txt
│   └── c.txt
└── 3
    └── d.txt

3 directories, 3 files

Once you run the application, it should delete all the files and corresponding directory structure will change like below.

Output directory structure
1
├── 2
│   └── 2.1
└── 3

Code Snippet
private static void deleteAllFiles(File dir) {
         for (File file : dir.listFiles()) {
                  if (file.isDirectory()) {
                           deleteAllFiles(file);
                           continue;
                  }
                  System.out.println("Deleting file : " + file.getAbsolutePath());
                  file.delete();

         }
}

Find the following working application.

App.java
package com.sample.app;

import java.io.File;

public class App {

 private static void deleteAllFiles(String filePath) {
  File file = new File(filePath);

  if (!file.isDirectory()) {
   return;
  }

  deleteAllFiles(file);
 }

 private static void deleteAllFiles(File dir) {
  for (File file : dir.listFiles()) {
   if (file.isDirectory()) {
    deleteAllFiles(file);
    continue;
   }
   System.out.println("Deleting file : " + file.getAbsolutePath());
   file.delete();

  }
 }

 public static void main(String args[]) {
  String folderPath = "/Users/Shared/1";

  deleteAllFiles(folderPath);
 }

}

Output
Deleting file : /Users/Shared/1/3/d.txt
Deleting file : /Users/Shared/1/2/2.1/b.txt
Deleting file : /Users/Shared/1/2/c.txt

You may like

No comments:

Post a Comment