How do I delete a file in a directory in Java?

Removing empty directory in Java is as simple as calling File.delete() (standard IO) or Files.delete() (NIO) method. However, if the folder is not empty (for example contains one or more files or subdirectories), these methods will refuse to remove it. In this post I want to present few ways to recursively remove the directory together with its contents.

Standard recursion (Java 6 and before)

The first method recursively removes files and directories from the directory tree starting from the leaves. Because it uses old I/O class File for operating on files and directories, this method can be used in any Java version.

void deleteDirectoryRecursionJava6(File file) throws IOException {
  if (file.isDirectory()) {
    File[] entries = file.listFiles();
    if (entries != null) {
      for (File entry : entries) {
        deleteDirectoryRecursionJava6(entry);
      }
    }
  }
  if (!file.delete()) {
    throw new IOException("Failed to delete " + file);
  }
}

Standard recursion using NIO (since Java 7)

Java 7 introduced improved API for I/O operations (also known as NIO). Once we decide to use it, the first method can be changed as follows:

void deleteDirectoryRecursion(Path path) throws IOException {
  if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) {
    try (DirectoryStream entries = Files.newDirectoryStream(path)) {
      for (Path entry : entries) {
        deleteDirectoryRecursion(entry);
      }
    }
  }
  Files.delete(path);
}

Walk tree (since Java 7)

Additionally, Java 7 introduced new method Files.walkFileTree() which traverses directory tree in the file-system using visitor design pattern. This new method can be easily used to recursively delete directory:

void deleteDirectoryWalkTree(Path path) throws IOException {
  FileVisitor visitor = new SimpleFileVisitor() {
            
    @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 {
      Files.delete(file);
      return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
      if (exc != null) {
        throw exc;
      }
      Files.delete(dir);
      return FileVisitResult.CONTINUE;
    }
  };
  Files.walkFileTree(path, visitor);
}

Streams and NIO2 (since Java 8)

Since Java 8 we can use Files.walk() method which behaves like this according to the official documentation:

Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the relative path against start.

The stream has to be sorted in reverse order first to prevent removal of non-empty directory. The final code looks like this:

void deleteDirectoryStream(Path path) throws IOException {
  Files.walk(path)
    .sorted(Comparator.reverseOrder())
    .map(Path::toFile)
    .forEach(File::delete);
}

However, this code has two drawbacks:

  • The stream is being sorted so all stream elements must be present in memory at the same time. This may significantly increase memory consumption for deep directory trees.
  • There is no error handling because the return value from File.delete() is ignored. This can be improved by using custom lambda inside forEach().

Apache Commons IO

Finally, there is a one-liner solution for the impatient. Just add Maven dependency:


   commons-io
   commons-io
   2.6

and call this single method:

FileUtils.deleteDirectory(file);

That’s all.

Conclusion

All of above methods should do the job. Personally, I prefer the last one because it is the simplest to use. The source code is available at GitHub.

About Robert Piasecki

Husband and father, Java software developer, Linux and open-source fan.

This entry was posted in Java, Maven, Uncategorized and tagged IO, Java, Maven, NIO. Bookmark the permalink.

This post will discuss how to delete all files in a directory in Java.

1. Using FileUtils class

The FileUtils class from Apache Commons IO offers several handy file manipulation utilities. You can use the FileUtils.cleanDirectory() method to recursively delete all files and subdirectories within a directory, without deleting the directory itself.

importorg.apache.commons.io.FileUtils;

importjava.io.File;

import java.io.IOException;

publicclassMain {

    publicstaticvoid main(String[]args)throws IOException{

        File directory=new File("/path/to/dir");

        FileUtils.cleanDirectory(directory);

    }

}

Download Code

 
To delete a directory recursively and everything in it, you can use the FileUtils.deleteDirectory() method.

importorg.apache.commons.io.FileUtils;

importjava.io.File;

import java.io.IOException;

publicclassMain {

    publicstaticvoid main(String[]args)throws IOException{

        File directory=new File("/path/to/dir");

        FileUtils.deleteDirectory(directory);

    }

}

Download Code

 
Alternatively, you can use the FileUtils.forceDelete() method to delete a directory and all subdirectories.

importorg.apache.commons.io.FileUtils;

importjava.io.File;

import java.io.IOException;

publicclassMain {

    publicstaticvoid main(String[]args)throws IOException{

        File directory=new File("/path/to/dir");

        FileUtils.forceDelete(directory);

    }

}

Download Code

2. Using File.delete() method

The File.delete() method deletes the file or directory denoted by the specified pathname. There are numerous ways to conditionally delete files and subdirectories in a directory using it.

For instance, the following solution only deletes files within the main directory, and all subdirectories remain untouched.

importjava.io.File;

import java.util.Objects;

publicclassMain {

    publicstaticvoid main(String[]args){

        File directory=newFile("/path/to/dir");

        for(File file: Objects.requireNonNull(directory.listFiles())) {

            if (!file.isDirectory()){

                file.delete();

            }

        }

    }

}

Download Code

 
If you use Java 8 or above, you can use:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

importjava.io.File;

import java.util.Arrays;

import java.util.Objects;

import java.util.function.Predicate;

publicclass Main{

    publicstaticvoid deleteDirectory(File directory){

        Arrays.stream(Objects.requireNonNull(directory.listFiles()))

                .filter(Predicate.not(File::isDirectory))

                .forEach(File::delete);

    }

    publicstaticvoid main(String[]args){

        File directory=newFile("/path/to/dir");

        deleteDirectory(directory);

    }

}

Download Code

 
You can easily extend the solution to recursively delete all files and subdirectories within a directory. Note that you can delete a directory using the File.delete() method if and only if the directory is empty.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

importjava.io.File;

import java.util.Objects;

publicclassMain {

    publicstaticvoiddeleteDirectory(File directory){

        for(File file: Objects.requireNonNull(directory.listFiles())) {

            if (file.isDirectory()){

                deleteDirectory(file);

            }else{

                file.delete();

            }

        }

    }

    publicstatic voidmain(String[]args){

        File directory=new File("/path/to/dir");

        deleteDirectory(directory);

    }

}

Download Code

 
Here’s a version using the Stream API. It takes advantage of the Files.walk() method and deletes all files and subdirectories within a directory, along with the directory itself.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

importjava.io.File;

import java.io.IOException;

import java.nio.file.Files;

import java.nio.file.Path;

import java.util.Comparator;

publicclassMain {

    publicstaticvoiddeleteDirectory(Path directory)throwsIOException{

        Files.walk(directory)

                .sorted(Comparator.reverseOrder())

                .map(Path::toFile)

                .forEach(File::delete);

    }

    publicstaticvoidmain(String[] args)throwsIOException{

        Path directory=Path.of("/path/to/dir");

        deleteDirectory(directory);

    }

}

Download Code

 
If you need to delete “only files” from the directory and all its subdirectories, you can do as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

importjava.io.File;

import java.io.IOException;

import java.nio.file.Files;

import java.nio.file.Path;

publicclass Main{

    publicstaticvoid deleteDirectory(File directory)throwsIOException{

        Files.walk(directory.toPath())

                .filter(Files::isRegularFile)

                .map(Path::toFile)

                .forEach(File::delete);

    }

    publicstaticvoidmain(String[] args)throwsIOException{

        File directory=newFile("/path/to/dir");

        deleteDirectory(directory);

    }

}

Download Code

That’s all about deleting all files in a directory in Java.

How do I delete files from a directory?

Locate the item you want to delete, highlight it by left-clicking the file or folder with your mouse once, and press the Delete key.

How can we delete all files in a directory in Java?

Method 1: using delete() to delete files and empty folders Provide the path of a directory. Call user-defined method deleteDirectory() to delete all the files and subfolders.

How do I delete multiple files in a directory in Java?

Using FileUtils class You can use the FileUtils. cleanDirectory() method to recursively delete all files and subdirectories within a directory, without deleting the directory itself. To delete a directory recursively and everything in it, you can use the FileUtils. deleteDirectory() method.

What are the 3 ways to delete a file or directory?

5 ways to delete files (temporarily or permanently) in Windows 10.
Delete or permanently delete files using keyboard shortcuts..
Delete files using the right-click menu..
Delete or permanently delete files from File Explorer's ribbon..
Permanently delete files using PowerShell or Command Prompt..