从java中删除文件夹

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

这段代码不起作用,最好的办法是什么?

如果你使用Apache Commons IO,它是一个单行的:

 FileUtils.deleteDirectory(dir); 

请参阅FileUtils.deleteDirectory()


番石榴曾经支持类似的function:

 Files.deleteRecursively(dir); 

这已经从番石榴几次发布前删除。


虽然上面的版本非常简单,但也是非常危险的,因为它没有告诉你很多假设。 所以虽然在大多数情况下可能是安全的,但我更喜欢“官方的方式”来做到这一点(自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; } }); }; 

我有这样的东西:

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

尝试这个:

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

这可能是嵌套文件夹的问题。 您的代码将按照发现的顺序删除文件夹,这是自顶向下的,不起作用。 如果您先倒转文件夹列表,它可能会起作用。

但我会build议你只使用像Commons IO这样的库。

我发现这段代码更加不可思议,并且工作正常:

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

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

检查这个问题

我曾经为此写了一个方法。 它删除指定的目录,如果目录删除成功,则返回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(); } 

您将所有(子)文件和文件夹以recursion方式存储在列表中,但使用当前的代码存储父文件夹, 然后再存储这些子文件夹。 所以你试图删除之前它是空的文件夹。 试试这个代码:

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

File.delete()的javadoc

public boolean delete()

删除由此抽象path名表示的文件或目录。 如果这个path名>表示一个目录,那么该目录必须是空的才能被删除。

所以一个文件夹必须是空的或删除它将失败。 您的代码当前将首先填充文件夹列表的顶部,然后是其子文件夹。 既然你通过列表​​以相同的方式通过列表,它会尝试删除最顶级的文件夹删除其子文件夹之前,这将失败。

改变这些线

  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,所以你可以检查这个值来做必要的error handling。

您应该首先删除文件夹中的文件,然后删除文件夹。这样您将recursion调用该方法。

它会recursion地删除一个文件夹

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