How to delete a folder with files using Java

社会主义新天地 提交于 2020-01-18 13:16:38

问题


I want to create and delete a directory using Java, but it isn't working.

File index = new File("/home/Work/Indexer1");
if (!index.exists()) {
    index.mkdir();
} else {
    index.delete();
    if (!index.exists()) {
        index.mkdir();
    }
}

回答1:


Java isn't able to delete folders with data in it. You have to delete all files before deleting the folder.

Use something like:

String[]entries = index.list();
for(String s: entries){
    File currentFile = new File(index.getPath(),s);
    currentFile.delete();
}

Then you should be able to delete the folder by using index.delete() Untested!




回答2:


Just a one-liner.

import org.apache.commons.io.FileUtils;

FileUtils.deleteDirectory(new File(destination));

Documentation here




回答3:


This works, and while it looks inefficient to skip the directory test, it's not: the test happens right away in listFiles().

void deleteDir(File file) {
    File[] contents = file.listFiles();
    if (contents != null) {
        for (File f : contents) {
            deleteDir(f);
        }
    }
    file.delete();
}

Update, to avoid following symbolic links:

void deleteDir(File file) {
    File[] contents = file.listFiles();
    if (contents != null) {
        for (File f : contents) {
            if (! Files.isSymbolicLink(f.toPath())) {
                deleteDir(f);
            }
        }
    }
    file.delete();
}



回答4:


In JDK 7 you could use Files.walkFileTree() and Files.deleteIfExists() to delete a tree of files.

In JDK 6 one possible way is to use FileUtils.deleteQuietly from Apache Commons which will remove a file, a directory, or a directory with files and sub-directories.




回答5:


I prefer this solution on java 8:

  Files.walk(pathToBeDeleted)
    .sorted(Comparator.reverseOrder())
    .map(Path::toFile)
    .forEach(File::delete);

From this site: http://www.baeldung.com/java-delete-directory




回答6:


Using Apache Commons-IO, it is following one-liner:

import org.apache.commons.io.FileUtils;

FileUtils.forceDelete(new File(destination));

This is (slightly) more performant than FileUtils.deleteDirectory.




回答7:


My basic recursive version, working with older versions of JDK:

public static void deleteFile(File element) {
    if (element.isDirectory()) {
        for (File sub : element.listFiles()) {
            deleteFile(sub);
        }
    }
    element.delete();
}



回答8:


This is the best solution for Java 7+:

public static void deleteDirectory(String directoryFilePath) throws IOException
{
    Path directory = Paths.get(directoryFilePath);

    if (Files.exists(directory))
    {
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>()
        {
            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException
            {
                Files.delete(path);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path directory, IOException ioException) throws IOException
            {
                Files.delete(directory);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}



回答9:


As mentioned, Java isn't able to delete a folder that contains files, so first delete the files and then the folder.

Here's a simple example to do this:

import org.apache.commons.io.FileUtils;



// First, remove files from into the folder 
FileUtils.cleanDirectory(folder/path);

// Then, remove the folder
FileUtils.deleteDirectory(folder/path);

Or:

FileUtils.forceDelete(new File(destination));



回答10:


Guava 21+ to the rescue. Use only if there are no symlinks pointing out of the directory to delete.

com.google.common.io.MoreFiles.deleteRecursively(
      file.toPath(),
      RecursiveDeleteOption.ALLOW_INSECURE
) ;

(This question is well-indexed by Google, so other people usig Guava might be happy to find this answer, even if it is redundant with other answers elsewhere.)




回答11:


I like this solution the most. It does not use 3rd party library, instead it uses NIO2 of Java 7.

/**
 * Deletes Folder with all of its content
 *
 * @param folder path to folder which should be deleted
 */
public static void deleteFolderAndItsContent(final Path folder) throws IOException {
    Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 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;
        }
    });
}



回答12:


In this

index.delete();

            if (!index.exists())
               {
                   index.mkdir();
               }

you are calling

 if (!index.exists())
                   {
                       index.mkdir();
                   }

after

index.delete();

This means that you are creating the file again after deleting File.delete() returns a boolean value.So if you want to check then do System.out.println(index.delete()); if you get true then this means that file is deleted

File index = new File("/home/Work/Indexer1");
    if (!index.exists())
       {
             index.mkdir();
       }
    else{
            System.out.println(index.delete());//If you get true then file is deleted




            if (!index.exists())
               {
                   index.mkdir();// here you are creating again after deleting the file
               }




        }

from the comments given below,the updated answer is like this

File f=new File("full_path");//full path like c:/home/ri
    if(f.exists())
    {
        f.delete();
    }
    else
    {
        try {
            //f.createNewFile();//this will create a file
            f.mkdir();//this create a folder
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



回答13:


If you have subfolders, you will find troubles with the Cemron answers. so you should create a method that works like this:

private void deleteTempFile(File tempFile) {
        try
        {
            if(tempFile.isDirectory()){
               File[] entries = tempFile.listFiles();
               for(File currentFile: entries){
                   deleteTempFile(currentFile);
               }
               tempFile.delete();
            }else{
               tempFile.delete();
            }
        getLogger().info("DELETED Temporal File: " + tempFile.getPath());
        }
        catch(Throwable t)
        {
            getLogger().error("Could not DELETE file: " + tempFile.getPath(), t);
        }
    }



回答14:


You can use FileUtils.deleteDirectory. JAVA can't delete the non-empty foldres with File.delete().




回答15:


directry cannot simply delete if it has the files so you may need to delete the files inside first and then directory

public class DeleteFileFolder {

public DeleteFileFolder(String path) {

    File file = new File(path);
    if(file.exists())
    {
        do{
            delete(file);
        }while(file.exists());
    }else
    {
        System.out.println("File or Folder not found : "+path);
    }

}
private void delete(File file)
{
    if(file.isDirectory())
    {
        String fileList[] = file.list();
        if(fileList.length == 0)
        {
            System.out.println("Deleting Directory : "+file.getPath());
            file.delete();
        }else
        {
            int size = fileList.length;
            for(int i = 0 ; i < size ; i++)
            {
                String fileName = fileList[i];
                System.out.println("File path : "+file.getPath()+" and name :"+fileName);
                String fullPath = file.getPath()+"/"+fileName;
                File fileOrFolder = new File(fullPath);
                System.out.println("Full Path :"+fileOrFolder.getPath());
                delete(fileOrFolder);
            }
        }
    }else
    {
        System.out.println("Deleting file : "+file.getPath());
        file.delete();
    }
}



回答16:


You can make recursive call if sub directories exists

import java.io.File;

class DeleteDir {
public static void main(String args[]) {
deleteDirectory(new File(args[0]));
}

static public boolean deleteDirectory(File path) {
if( path.exists() ) {
  File[] files = path.listFiles();
  for(int i=0; i<files.length; i++) {
     if(files[i].isDirectory()) {
       deleteDirectory(files[i]);
     }
     else {
       files[i].delete();
     }
  }
}
return( path.delete() );
}
}



回答17:


we can use the spring-core dependency;

boolean result = FileSystemUtils.deleteRecursively(file);



回答18:


Most of answers (even recent) referencing JDK classes rely on File.delete() but that is a flawed API as the operation may fail silently.
The java.io.File.delete() method documentation states :

Note that the java.nio.file.Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

As replacement, you should favor Files.delete(Path p) that throws an IOException with a error message.

The actual code could be written such as :

Path index = Paths.get("/home/Work/Indexer1");

if (!Files.exists(index)) {
    index = Files.createDirectories(index);
} else {

    Files.walk(index)
         .sorted(Comparator.reverseOrder())  // as the file tree is traversed depth-first and that deleted dirs have to be empty  
         .forEach(t -> {
             try {
                 Files.delete(t);
             } catch (IOException e) {
                 // LOG the exception and potentially stop the processing

             }
         });
    if (!Files.exists(index)) {
        index = Files.createDirectories(index);
    }
}



回答19:


you can try as follows

  File dir = new File("path");
   if (dir.isDirectory())
   {
         dir.delete();
   }

If there are sub folders inside your folder you may need to recursively delete them.




回答20:


private void deleteFileOrFolder(File file){
    try {
        for (File f : file.listFiles()) {
            f.delete();
            deleteFileOrFolder(f);
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}



回答21:


        import org.apache.commons.io.FileUtils;

        List<String> directory =  new ArrayList(); 
        directory.add("test-output"); 
        directory.add("Reports/executions"); 
        directory.add("Reports/index.html"); 
        directory.add("Reports/report.properties"); 
        for(int count = 0 ; count < directory.size() ; count ++)
        {
        String destination = directory.get(count);
        deleteDirectory(destination);
        }





      public void deleteDirectory(String path) {

        File file  = new File(path);
        if(file.isDirectory()){
             System.out.println("Deleting Directory :" + path);
            try {
                FileUtils.deleteDirectory(new File(path)); //deletes the whole folder
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else {
        System.out.println("Deleting File :" + path);
            //it is a simple file. Proceed for deletion
            file.delete();
        }

    }

Works like a Charm . For both folder and files . Salam :)




回答22:


One more choice is to use Spring's org.springframework.util.FileSystemUtils relevant method which will recursively delete all content of the directory.

File directoryToDelete = new File(<your_directory_path_to_delete>);
FileSystemUtils.deleteRecursively(directoryToDelete);

That will do the job!




回答23:


Remove it from else part

File index = new File("/home/Work/Indexer1");
if (!index.exists())
{
     index.mkdir();
     System.out.println("Dir Not present. Creating new one!");
}
index.delete();
System.out.println("File deleted successfully");



回答24:


Some of these answers seem unnecessarily long:

if (directory.exists()) {
    for (File file : directory.listFiles()) {
        file.delete();
    }
    directory.delete();
}

Works for sub directories too.




回答25:


import java.io.File;

public class Main{
   public static void main(String[] args) throws Exception {
      deleteDir(new File("c:\\temp"));
   }
   public static boolean deleteDir(File dir) {
      if (dir.isDirectory()) {
         String[] children = dir.list();
         for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir (new File(dir, children[i]));

            if (!success) {
               return false;
            }
         }
      }
      return dir.delete();
      System.out.println("The directory is deleted.");
   }
}



回答26:


You can use this function

public void delete()    
{   
    File f = new File("E://implementation1/");
    File[] files = f.listFiles();
    for (File file : files) {
        file.delete();
    }
}


来源:https://stackoverflow.com/questions/20281835/how-to-delete-a-folder-with-files-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!