0

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

user3678528
  • 1,741
  • 2
  • 18
  • 24
Imane Jabal
  • 35
  • 1
  • 9

1 Answers1

1

In directories you will need to do this for each file. You can check .isDirectory() and if so loop around each file in there from .listFiles() until you've completed everything inside of the root directory passed to the method.

Java 8 also now offers Files.walk to do this a bit easier, check out the documentation here.