0

I'm writing some files to a folder.

But when I reuse that folder I want to delete every file in that directory. The problem is that I don't know if this directory actually exists or not.

final String fileDir = "myPath/someDir/;
// If this dir exists, delete every file inside
//Populate this dir ( I have this code)
  • 3
    Possible duplicate of [Create directory. If exists, delete directory and its content and create new one in Java](https://stackoverflow.com/questions/12835285/create-directory-if-exists-delete-directory-and-its-content-and-create-new-one) – Héctor Mar 09 '18 at 11:02
  • but I have a string, not a file. –  Mar 09 '18 at 11:03
  • 2
    `File file = new File(fileDir);` You can pass the String to file – Jay Shankar Gupta Mar 09 '18 at 11:05
  • Possible duplicate of [Is there a proper way to check for file/directory existence in Java?](https://stackoverflow.com/questions/7996524/is-there-a-proper-way-to-check-for-file-directory-existence-in-java) – Mehmet Sunkur Mar 09 '18 at 11:07

3 Answers3

1

This the way to check if file exists

if(f.exists() && !f.isDirectory()) { 
    // delete
}
xMilos
  • 1,519
  • 4
  • 21
  • 36
1

In package java.nio.file you have very handy utils (from java7):

Files.deleteIfExists(path)

and if you want to delete recursively sth like:

Path path = Paths.get("/path/to/your/dir");
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

   @Override
   public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
       Files.delete(file);
       return FileVisitResult.CONTINUE;
   }

   @Override
   public FileVisitResult postVisitDirectory(Path directory, IOException exception) throws IOException {
       Files.delete(directory);
       return FileVisitResult.CONTINUE;
   }

});
Maciej
  • 1,954
  • 10
  • 14
0

Use org.apache.commons.io.FileUtils class

FileUtils.cleanDirectory(directory);

There is this method available in the same file. This will also recursively deletes all sub-folders and files under them.

final String fileDir = "myPath/someDir/";
File dir = new File(fileDir);
FileUtils.cleanDirectory(dir);
nkr
  • 3,026
  • 7
  • 31
  • 39
Hassan Mudassir
  • 191
  • 2
  • 10