How can I delete entire directories with contents in Java? I've tried some codes but it doesn't work.
public static void removeRecursive(Path path) throws IOException
{
Files.walkFileTree(path, new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException
{
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException
{
// try to delete the file anyway, even if its attributes
// could not be read, since delete-only access is
// theoretically possible
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException
{
if (exc == null)
{
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
else
{
// directory iteration failed; propagate exception
throw exc;
}
}
});
}
It throws as an error :
D:\MainDir\chantier : Erreur de lecture. String index out of range: -1
And here is my path D:\MainDir\ch\Lot\dossier\mail.zip
And I want to delete directory ch\Lot\dossier\mail.zip with his contents but my function remove only \dossier\mail.zip and throws the error mentioned
Ps : I give as an input file D:\MainDir\ch
Thanks in advance