如何使用Java删除包含文件的文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20281835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:49:31  来源:igfitidea点击:

How to delete a folder with files using Java

javafile-iodelete-directory

提问by Mr.G

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

我想使用 Java 创建和删除一个目录,但它不起作用。

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

采纳答案by Cemron

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

Java 无法删除包含数据的文件夹。在删除文件夹之前,您必须删除所有文件。

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!

然后您应该可以使用index.delete()Untested删除该文件夹!

回答by Aniket Thakur

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");

回答by SpringLearner

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 truethen this means that file is deleted

这意味着您在删除File.delete()返回一个布尔值后再次创建文件。 所以如果你想检查然后System.out.println(index.delete());如果你得到true那么这意味着文件被删除

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 commentsgiven 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();
        }
    }

回答by Ruchira Gayan Ranaweera

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.

如果您的文件夹中有子文件夹,您可能需要递归删除它们。

回答by Andrey Chaschev

In JDK 7 you could use Files.walkFileTree()and Files.deleteIfExists()to delete a tree of files. (Sample: http://fahdshariff.blogspot.ru/2011/08/java-7-deleting-directory-by-walking.html)

在 JDK 7 中,您可以使用Files.walkFileTree()Files.deleteIfExists()删除文件树。(示例:http: //fahdshariff.blogspot.ru/2011/08/java-7-deleting-directory-by-walking.html

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

在 JDK 6 中,一种可能的方法是使用Apache Commons 中的FileUtils.deleteQuietly,它将删除文件、目录或包含文件和子目录的目录。

回答by Indranil.Bharambe

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();
    }
}

回答by Panthro

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

如果您有子文件夹,您会发现 Cemron 答案有问题。所以你应该创建一个像这样工作的方法:

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);
        }
    }

回答by Barry Knapp

Just a one-liner.

只是一个班轮。

import org.apache.commons.io.FileUtils;

FileUtils.deleteDirectory(new File(destination));

Documentation here

文档在这里

回答by Marcelo Lopes

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

回答by JRA_TLL

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

使用 Apache Commons-IO,它遵循单线:

import org.apache.commons.io.FileUtils;

FileUtils.forceDelete(new File(destination));

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

这比FileUtils.deleteDirectory.