无法使用 Java 删除文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22085706/
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 13:30:39  来源:igfitidea点击:

Cannot delete folder using Java

javafilefile-iojava-io

提问by TV Nath

I am trying to delete a folder which has only files but no sub folders without success.

我试图删除一个只有文件但没有子文件夹的文件夹,但没有成功。

Code:

代码:

File rowFolder = new File(folderPath);
String[] files = rowFolder.list();
for (String file : files){
    File deleteFile = new File(file);
    System.out.println("deleting file -"+deleteFile.getName());
    deleteFile.delete();
}
System.out.println("deleting folder -"+rowFolder.getName());
rowFolder.delete();

Output:

输出:

deleting file -testing.pdf
deleting file -app_json.json
deleting file -photo.jpg
deleting folder -bundle_folder

The code doesn't delete any folder nor any file. Why is that?

该代码不会删除任何文件夹或任何文件。这是为什么?

采纳答案by Durandal

You could be getting a failed delete for a number of reasons; the file could be locked by the file system, you may lack permissions, or could be open by another process etc.

由于多种原因,您可能会遇到删除失败的情况;该文件可能被文件系统锁定,您可能缺乏权限,或者可能被另一个进程打开等。

If you're using Java 7 or above you can use the javax.nio.*API; it's a little more reliable & consistent than the legacyjava.io.Fileclasses:

如果您使用的是 Java 7 或更高版本,则可以使用javax.nio.*API;它比遗留java.io.File类更可靠和一致:

Path fp = file.toPath();
Files.delete(fp);

If you want to catch the possible exceptions:

如果要捕获可能的异常:

try {
    Files.delete(path);
} catch (NoSuchFileException x) {
    System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
    System.err.format("%s not empty%n", path);
} catch (IOException x) {
    // File permission problems are caught here.
    System.err.println(x);
}

Check the docsfor more info on IO in Java 7

查看文档以获取有关 Java 7 中 IO 的更多信息

回答by Bishan

Try this. Source: How To Delete Directory In Java

尝试这个。来源:如何在 Java 中删除目录

import java.io.File;
import java.io.IOException;

public class DeleteDirectoryExample
{
    private static final String SRC_FOLDER = "C:\mkyong-new";

    public static void main(String[] args)
    {   

        File directory = new File(SRC_FOLDER);

        //make sure directory exists
        if(!directory.exists()){

           System.out.println("Directory does not exist.");
           System.exit(0);

        }else{

           try{

               delete(directory);

           }catch(IOException e){
               e.printStackTrace();
               System.exit(0);
           }
        }

        System.out.println("Done");
    }

    public static void delete(File file)
        throws IOException{

        if(file.isDirectory()){

            //directory is empty, then delete it
            if(file.list().length==0){

               file.delete();
               System.out.println("Directory is deleted : " 
                                                 + file.getAbsolutePath());

            }else{

               //list all the directory contents
               String files[] = file.list();

               for (String temp : files) {
                  //construct the file structure
                  File fileDelete = new File(file, temp);

                  //recursive delete
                 delete(fileDelete);
               }

               //check the directory again, if empty then delete it
               if(file.list().length==0){
                 file.delete();
                 System.out.println("Directory is deleted : " 
                                                  + file.getAbsolutePath());
               }
            }

        }else{
            //if file, then delete it
            file.delete();
            System.out.println("File is deleted : " + file.getAbsolutePath());
        }
    }
}

回答by user207421

As you aren't checking the return value of delete(), the output you produce is meaningless. The deletion could have failed for any number of reasons:

由于您没有检查 delete() 的返回值,因此您生成的输出毫无意义。删除可能因多种原因而失败:

  • the file is a non-empty directory
  • the file is open by another user (on some platforms)
  • you don't have permission to delete that file.
  • 该文件是一个非空目录
  • 该文件由另一个用户打开(在某些平台上)
  • 您无权删除该文件。

回答by Sai Ye Yan Naing Aye

Try this code

试试这个代码

 public class DeleteDirTest {
    public static void main(String[] args) throws IOException {
        DeleteDirTest test = new DeleteDirTest();
        boolean result = test.deleteDir(new File("D:/test"));
        System.out.println(result);         
    }

    public boolean deleteDir(File file) {
        if (file.isDirectory()) {
            String[] children = file.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(file, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return file.delete();
    }

}