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

3 Answers 3

1

This the way to check if file exists

if(f.exists() && !f.isDirectory()) { // delete } 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

4 Comments

it expects a file not a string with the dir
Create a file object out of it. new File("myPath/someDir");
I got error saying the dir doesn't exist (and it doesn't). i just need an if if(dir.exists() ??
This is the basic thing that you need to change the path to actual directory path. :O