如何使用Java删除文件文件夹

时间:2021-06-03 15:55:19

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

21 个解决方案

#1


60  

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()来删除未测试的文件夹!

#2


114  

Just a one-liner.

只是一个小笑话。

import org.apache.commons.io.FileUtils;

FileUtils.deleteDirectory(new File(destination));

Documentation here

文件在这里

#3


81  

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

这是可行的,尽管跳过目录测试看起来效率不高,但它不是:测试马上就在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


19  

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

在JDK 7中,可以使用Files.walkFileTree()和Files.deleteIfExists()来删除文件树。

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.

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

#5


13  

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

使用Apache common - io,它遵循一行代码:

import org.apache.commons.io.FileUtils;

FileUtils.forceDelete(new File(destination));

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

这比FileUtils.deleteDirectory的性能稍好。

#6


9  

I prefer this solution on java 8:

我更喜欢java 8的这种解决方案:

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

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

从这个网站:http://www.baeldung.com/java-delete-directory

#7


7  

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

我的基本递归版本,使用JDK的旧版本:

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

#8


5  

This is the best solution for Java 7+:

这是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


4  

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

我最喜欢这个解决方案。它不使用第三方库,而是使用Java 7的NIO2。

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

#10


2  

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

#11


2  

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

番石榴21+的救援。只有在没有指向目录下的符号链接删除时才使用。

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.)

(这个问题被谷歌很好地索引,所以其他人也许会很高兴找到这个答案,即使它与其他答案是多余的。)

#12


1  

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

如果directry有文件,它不能简单地删除,因此您可能需要先删除目录内的文件,然后再删除目录

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

#13


1  

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

#14


1  

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

#15


1  

Some of these answers seem unnecessarily long:

其中一些答案似乎不必要地太长:

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

Works for sub directories too.

也适用于子目录。

#16


0  

Remove it from else part

把它从else部分删除。

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

#17


0  

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.

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

#18


0  

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

#19


0  

        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 :)

工作起来很有魅力。用于文件夹和文件。萨拉姆:)

#20


-1  

Create directory -

创建目录,

File directory = new File("D:/Java/Example");
boolean isCreated = directory.mkdir();

Delete directory -

删除目录,

Refer this resource for detailed explanation - delete directory.

有关详细说明-删除目录,请参阅此资源。

#21


-2  

You can use this function

你可以用这个函数

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

#1


60  

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()来删除未测试的文件夹!

#2


114  

Just a one-liner.

只是一个小笑话。

import org.apache.commons.io.FileUtils;

FileUtils.deleteDirectory(new File(destination));

Documentation here

文件在这里

#3


81  

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

这是可行的,尽管跳过目录测试看起来效率不高,但它不是:测试马上就在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


19  

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

在JDK 7中,可以使用Files.walkFileTree()和Files.deleteIfExists()来删除文件树。

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.

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

#5


13  

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

使用Apache common - io,它遵循一行代码:

import org.apache.commons.io.FileUtils;

FileUtils.forceDelete(new File(destination));

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

这比FileUtils.deleteDirectory的性能稍好。

#6


9  

I prefer this solution on java 8:

我更喜欢java 8的这种解决方案:

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

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

从这个网站:http://www.baeldung.com/java-delete-directory

#7


7  

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

我的基本递归版本,使用JDK的旧版本:

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

#8


5  

This is the best solution for Java 7+:

这是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


4  

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

我最喜欢这个解决方案。它不使用第三方库,而是使用Java 7的NIO2。

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

#10


2  

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

#11


2  

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

番石榴21+的救援。只有在没有指向目录下的符号链接删除时才使用。

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.)

(这个问题被谷歌很好地索引,所以其他人也许会很高兴找到这个答案,即使它与其他答案是多余的。)

#12


1  

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

如果directry有文件,它不能简单地删除,因此您可能需要先删除目录内的文件,然后再删除目录

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

#13


1  

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

#14


1  

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

#15


1  

Some of these answers seem unnecessarily long:

其中一些答案似乎不必要地太长:

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

Works for sub directories too.

也适用于子目录。

#16


0  

Remove it from else part

把它从else部分删除。

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

#17


0  

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.

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

#18


0  

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

#19


0  

        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 :)

工作起来很有魅力。用于文件夹和文件。萨拉姆:)

#20


-1  

Create directory -

创建目录,

File directory = new File("D:/Java/Example");
boolean isCreated = directory.mkdir();

Delete directory -

删除目录,

Refer this resource for detailed explanation - delete directory.

有关详细说明-删除目录,请参阅此资源。

#21


-2  

You can use this function

你可以用这个函数

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