从java中删除文件夹

发布于 2024-09-24 13:42:26 字数 1114 浏览 0 评论 0原文

在Java中,我想删除包含文件和文件夹的文件夹中存在的所有内容。

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);
            tempFile.delete();
        }
        for(String filePath : folderList) {
            File tempFile = new File(filePath);
            tempFile.delete();
        }
    }

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.add(tempFile.getAbsolutePath());
            fetchCompleteList(filesList, 
                folderList, tempFile.getAbsolutePath());
        } else {
            filesList.add(tempFile.getAbsolutePath());
        }

    }

}

此代码不起作用,执行此操作的最佳方法是什么?

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);
            tempFile.delete();
        }
        for(String filePath : folderList) {
            File tempFile = new File(filePath);
            tempFile.delete();
        }
    }

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.add(tempFile.getAbsolutePath());
            fetchCompleteList(filesList, 
                folderList, tempFile.getAbsolutePath());
        } else {
            filesList.add(tempFile.getAbsolutePath());
        }

    }

}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

仙气飘飘 2024-10-01 13:42:26

如果您使用 Apache Commons IO,那么它只是一句:

FileUtils.deleteDirectory(dir);

请参阅 FileUtils.deleteDirectory()



Guava 用于支持类似功能:

Files.deleteRecursively(dir);


这已在几个版本之前从 Guava 中删除。


虽然上面的版本非常简单,但它也非常危险,因为它在没有告诉你的情况下做出了很多假设。因此,虽然在大多数情况下它可能是安全的,但我更喜欢“官方方式”来执行此操作(从 Java 7 开始):

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 {
      Files.delete(file);
      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);
      Files.delete(dir);
      return CONTINUE;
    }
  });
};

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

FileUtils.deleteDirectory(dir);

See FileUtils.deleteDirectory()



Guava used to support similar functionality:

Files.deleteRecursively(dir);


This has been removed from Guava several releases ago.


While the above version is very simple, it is also pretty dangerous, as it makes a lot of assumptions without telling you. So while it may be safe in most cases, I prefer the "official way" to do it (since Java 7):

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 {
      Files.delete(file);
      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);
      Files.delete(dir);
      return CONTINUE;
    }
  });
};
绝不服输 2024-10-01 13:42:26

我有这样的东西:

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

I have something like this :

public static boolean deleteDirectory(File directory) {
    if(directory.exists()){
        File[] files = directory.listFiles();
        if(null!=files){
            for(int i=0; i<files.length; i++) {
                if(files[i].isDirectory()) {
                    deleteDirectory(files[i]);
                }
                else {
                    files[i].delete();
                }
            }
        }
    }
    return(directory.delete());
}
奢华的一滴泪 2024-10-01 13:42:26

试试这个:

public static boolean deleteDir(File dir) 
{ 
  if (dir.isDirectory()) 
  { 
    String[] children = dir.list(); 
    for (int i=0; i<children.length; i++)
      return deleteDir(new File(dir, children[i])); 
  }  
  // The directory is now empty or this is a file so delete it 
  return dir.delete(); 
} 

Try this:

public static boolean deleteDir(File dir) 
{ 
  if (dir.isDirectory()) 
  { 
    String[] children = dir.list(); 
    for (int i=0; i<children.length; i++)
      return deleteDir(new File(dir, children[i])); 
  }  
  // The directory is now empty or this is a file so delete it 
  return dir.delete(); 
} 
伊面 2024-10-01 13:42:26

嵌套文件夹可能有问题。您的代码按照找到文件夹的顺序删除文件夹,这是自上而下的,这是行不通的。如果您先反转文件夹列表,它可能会起作用。

但我建议您为此使用像 Commons IO 这样的库。

It could be problem with nested folders. Your code deletes the folders in the order they were found, which is top-down, which does not work. It might work if you reverse the folder list first.

But I would recommend you just use a library like Commons IO for this.

巨坚强 2024-10-01 13:42:26

我发现这段代码更容易理解并且更有效:

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(); // The directory is empty now and can be deleted.
}

I found this piece of code more understadable and working:

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(); // The directory is empty now and can be deleted.
}
水水月牙 2024-10-01 13:42:26

使用 FileUtils.deleteDirectory() 方法可以帮助简化递归删除目录及其下面所有内容的过程。

检查这个问题

Using the FileUtils.deleteDirectory() method can help to simplify the process of deleting directory and everything below it recursively.

Check this question

泪眸﹌ 2024-10-01 13:42:26

我之前为此写了一个方法。删除指定目录,如果目录删除成功则返回true。

/**
 * Delets a dir recursively deleting anything inside it.
 * @param dir The dir to delete
 * @return true if the dir was successfully deleted
 */
public static boolean deleteDirectory(File dir) {
    if(! dir.exists() || !dir.isDirectory())    {
        return false;
    }

    String[] files = dir.list();
    for(int i = 0, len = files.length; i < len; i++)    {
        File f = new File(dir, files[i]);
        if(f.isDirectory()) {
            deleteDirectory(f);
        }else   {
            f.delete();
        }
    }
    return dir.delete();
}

I wrote a method for this sometime back. It deletes the specified directory and returns true if the directory deletion was successful.

/**
 * Delets a dir recursively deleting anything inside it.
 * @param dir The dir to delete
 * @return true if the dir was successfully deleted
 */
public static boolean deleteDirectory(File dir) {
    if(! dir.exists() || !dir.isDirectory())    {
        return false;
    }

    String[] files = dir.list();
    for(int i = 0, len = files.length; i < len; i++)    {
        File f = new File(dir, files[i]);
        if(f.isDirectory()) {
            deleteDirectory(f);
        }else   {
            f.delete();
        }
    }
    return dir.delete();
}
櫻之舞 2024-10-01 13:42:26

您将所有(子)文件和文件夹递归存储在列表中,但使用当前代码,您将在存储子文件夹之前存储父文件夹。因此,您尝试在文件夹为空之前将其删除。试试这个代码:

   if(tempFile.isDirectory()) {
        // children first
        fetchCompleteList(filesList, folderList, tempFile.getAbsolutePath());
        // parent folder last
        folderList.add(tempFile.getAbsolutePath());
   }

You're storing all (sub-) files and folder recursively in a list, but with your current code you store the parent folder before you store the children. And so you try to delete the folder before it is empty. Try this code:

   if(tempFile.isDirectory()) {
        // children first
        fetchCompleteList(filesList, folderList, tempFile.getAbsolutePath());
        // parent folder last
        folderList.add(tempFile.getAbsolutePath());
   }
孤君无依 2024-10-01 13:42:26

文件的 javadoc .delete()

公共布尔删除()

删除此抽象路径名表示的文件或目录。如果此路径名>表示目录,则该目录必须为空才能删除。

所以文件夹必须是空的,否则删除会失败。您的代码当前首先使用最顶层的文件夹填充文件夹列表,然后是其子文件夹。由于您以相同的方式遍历列表,它将尝试在删除其子文件夹之前删除最顶层的文件夹,因此这将失败。

将这些行更改

    for(String filePath : folderList) {
        File tempFile = new File(filePath);
        tempFile.delete();
    }

为此

    for(int i = folderList.size()-1;i>=0;i--) {
        File tempFile = new File(folderList.get(i));
        tempFile.delete();
    }

应该会导致您的代码首先删除子文件夹。

删除操作失败时也会返回 false,因此您可以检查该值以在必要时进行一些错误处理。

The javadoc for File.delete()

public boolean delete()

Deletes the file or directory denoted by this abstract pathname. If this pathname >denotes a directory, then the directory must be empty in order to be deleted.

So a folder has to be empty or deleting it will fail. Your code currently fills the folder list with the top most folder first, followed by its sub folders. Since you iterrate through the list in the same way it will try to delete the top most folder before deleting its subfolders, this will fail.

Changing these line

    for(String filePath : folderList) {
        File tempFile = new File(filePath);
        tempFile.delete();
    }

to this

    for(int i = folderList.size()-1;i>=0;i--) {
        File tempFile = new File(folderList.get(i));
        tempFile.delete();
    }

should cause your code to delete the sub folders first.

The delete operation also returns false when it fails, so you can check this value to do some error handling if necessary.

野の 2024-10-01 13:42:26

你应该先删除文件夹中的文件,然后删除文件夹。这样你就会递归地调用该方法。

You should delete the file in the folder first , then the folder.This way you will recursively call the method.

攒眉千度 2024-10-01 13:42:26

它将递归删除文件夹

public static void folderdel(String path){
    File f= new File(path);
    if(f.exists()){
        String[] list= f.list();
        if(list.length==0){
            if(f.delete()){
                System.out.println("folder deleted");
                return;
            }
        }
        else {
            for(int i=0; i<list.length ;i++){
                File f1= new File(path+"\\"+list[i]);
                if(f1.isFile()&& f1.exists()){
                    f1.delete();
                }
                if(f1.isDirectory()){
                    folderdel(""+f1);
                }
            }
            folderdel(path);
        }
    }
}

It will delete a folder recursively

public static void folderdel(String path){
    File f= new File(path);
    if(f.exists()){
        String[] list= f.list();
        if(list.length==0){
            if(f.delete()){
                System.out.println("folder deleted");
                return;
            }
        }
        else {
            for(int i=0; i<list.length ;i++){
                File f1= new File(path+"\\"+list[i]);
                if(f1.isFile()&& f1.exists()){
                    f1.delete();
                }
                if(f1.isDirectory()){
                    folderdel(""+f1);
                }
            }
            folderdel(path);
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文