M.J. M.J. - 7 months ago 20
Java Question

deleting folder from java

In Java, I want to delete all the contents that are present in a folder which includes files and folders.

public void startDeleting(String path) {
List<String> filesList = new ArrayList<String>();
List<String> folderList = new ArrayList<String>();
fetchCompleteList(filesList, folderList, path);
for(String filePath : filesList) {
File tempFile = new File(filePath);
for(String filePath : folderList) {
File tempFile = new File(filePath);

private void fetchCompleteList(List<String> filesList,
List<String> folderList, String path) {
File file = new File(path);
File[] listOfFile = file.listFiles();
for(File tempFile : listOfFile) {
if(tempFile.isDirectory()) {
folderList, tempFile.getAbsolutePath());
} else {



This code does not work, what is the best way to do this?


Pre-Java-7, using a library would have been the best choice.

If you use Apache Commons IO it's a one-liner:


See FileUtils.deleteDirectory()

Guava used to support similar functionality:


This has been removed from Guava several releases ago.

Ever since Java 7, this is the preferred way to do it:

public static void deleteFileOrFolder(final Path path) throws IOException {
  Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
    @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
      throws IOException {
      return CONTINUE;

    @Override public FileVisitResult visitFileFailed(final Path file, final IOException e) {
      return handleException(e);

    private FileVisitResult handleException(final IOException e) {
      e.printStackTrace(); // replace with more robust error handling
      return TERMINATE;

    @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException e)
      throws IOException {
      if(e!=null)return handleException(e);
      return CONTINUE;