簡體   English   中英

如何使用 Java 刪除包含文件的文件夾

[英]How to delete a folder with files using Java

我想使用 Java 創建和刪除目錄,但它不起作用。

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

只是一個班輪。

import org.apache.commons.io.FileUtils;

FileUtils.deleteDirectory(new File(destination));

文檔在這里

Java 無法刪除包含數據的文件夾。 在刪除文件夾之前,您必須刪除所有文件。

使用類似的東西:

String[]entries = index.list();
for(String s: entries){
    File currentFile = new File(index.getPath(),s);
    currentFile.delete();
}

然后你應該可以使用index.delete()來刪除文件夾 未經測試!

這有效,雖然跳過目錄測試看起來效率低下,但事實並非如此:測試立即發生在listFiles()

void deleteDir(File file) {
    File[] contents = file.listFiles();
    if (contents != null) {
        for (File f : contents) {
            deleteDir(f);
        }
    }
    file.delete();
}

更新,以避免以下符號鏈接:

void deleteDir(File file) {
    File[] contents = file.listFiles();
    if (contents != null) {
        for (File f : contents) {
            if (! Files.isSymbolicLink(f.toPath())) {
                deleteDir(f);
            }
        }
    }
    file.delete();
}

我更喜歡 java 8 上的這個解決方案:

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

從這個網站: http : //www.baeldung.com/java-delete-directory

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

在 JDK 6 中,一種可能的方法是使用 Apache Commons 中的FileUtils.deleteQuietly ,它將刪除文件、目錄或包含文件和子目錄的目錄。

使用 Apache Commons-IO,它遵循單線:

import org.apache.commons.io.FileUtils;

FileUtils.forceDelete(new File(destination));

這(略)比FileUtils.deleteDirectory性能更高。

如前所述, Java無法刪除包含文件的文件夾,因此請先刪除文件,然后再刪除文件夾。

這是一個簡單的例子來做到這一點:

import org.apache.commons.io.FileUtils;



// First, remove files from into the folder 
FileUtils.cleanDirectory(folder/path);

// Then, remove the folder
FileUtils.deleteDirectory(folder/path);

或者:

FileUtils.forceDelete(new File(destination));

我的基本遞歸版本,使用舊版本的 JDK:

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

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

另一種選擇是使用 Spring 的org.springframework.util.FileSystemUtils相關方法,它將遞歸刪除目錄的所有內容。

File directoryToDelete = new File(<your_directory_path_to_delete>);
FileSystemUtils.deleteRecursively(directoryToDelete);

這將完成工作!

番石榴 21+ 來救援。 僅當沒有指向要刪除的目錄外的符號鏈接時才使用。

com.google.common.io.MoreFiles.deleteRecursively(
      file.toPath(),
      RecursiveDeleteOption.ALLOW_INSECURE
) ;

(此問題已被 Google 編入索引,因此使用 Guava 的其他人可能會很高興找到此答案,即使它與其他地方的其他答案是多余的。)

我最喜歡這個解決方案。 它不使用第 3 方庫,而是使用 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;
        }
    });
}

你可以試試這個

public static void deleteDir(File dirFile) {
    if (dirFile.isDirectory()) {
        File[] dirs = dirFile.listFiles();
        for (File dir: dirs) {
            deleteDir(dir);
        }
    }
    dirFile.delete();
}

在這

index.delete();

            if (!index.exists())
               {
                   index.mkdir();
               }

你在打電話

 if (!index.exists())
                   {
                       index.mkdir();
                   }

之后

index.delete();

這意味着你在刪除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
               }




        }

從下面給出的評論中,更新的答案是這樣的

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

如果您有子文件夾,您會發現 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);
        }
    }

您可以使用FileUtils.deleteDirectory JAVA 無法使用File.delete()刪除非空文件夾。

2020 在這里:)

使用 Apache commons io FileUtils,與“純”Java 變體相反,文件夾不需要為空即可刪除。 為了給你一個更好的概覽,我在這里列出了這些變體,以下 3 個可能由於各種原因拋出異常:

  • cleanDirectory :清理目錄而不刪除它
  • forceDelete :刪除文件。 如果文件是一個目錄,刪除它和所有子目錄
  • forceDeleteOnExit :在 JVM 退出時安排要刪除的文件。 如果文件是目錄刪除它和所有子目錄。 不推薦用於運行服務器,因為 JVM 可能不會很快退出......

以下變體永遠不會引發異常(即使文件為 null !)

  • deleteQuietly :刪除文件,從不拋出異常 如果是目錄,刪除它和所有子目錄。

要知道的另一件事是處理符號鏈接,它會刪除符號鏈接而不是目標文件夾......小心。

還要記住,刪除大文件或文件夾可能會在一段時間內成為阻塞操作......所以如果你不介意讓它異步運行(例如在后台線程中通過執行程序)。

如果目錄中有文件,則不能簡單地刪除,因此您可能需要先刪除里面的文件,然后再刪除目錄

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

如果子目錄存在,您可以進行遞歸調用

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

我們可以使用spring-core依賴;

boolean result = FileSystemUtils.deleteRecursively(file);

大多數引用 JDK 類的答案(甚至是最近的)都依賴於File.delete()但這是一個有缺陷的 API,因為操作可能會靜默失敗。
java.io.File.delete()方法文檔說明:

請注意, java.nio.file.Files類定義了delete方法,以便在無法刪除文件時拋出IOException 這對於錯誤報告和診斷無法刪除文件的原因很有用。

作為替代,您應該支持Files.delete(Path p)拋出帶有錯誤消息的IOException

實際的代碼可以這樣寫:

Path index = Paths.get("/home/Work/Indexer1");

if (!Files.exists(index)) {
    index = Files.createDirectories(index);
} else {

    Files.walk(index)
         .sorted(Comparator.reverseOrder())  // as the file tree is traversed depth-first and that deleted dirs have to be empty  
         .forEach(t -> {
             try {
                 Files.delete(t);
             } catch (IOException e) {
                 // LOG the exception and potentially stop the processing

             }
         });
    if (!Files.exists(index)) {
        index = Files.createDirectories(index);
    }
}
You can simply remove the directory which contains a single file or multiple files using the apache commons library.

gradle 進口:

實施組:'commons-io',名稱:'commons-io',版本:'2.5'

File file=new File("/Users/devil/Documents/DummyProject/hello.txt");
    
 File parentDirLocation=new File(file.getParent);
    
//Confirming the file parent is a directory or not.
             
if(parentDirLocation.isDirectory){
    
    
 //after this line the mentioned directory will deleted.
 FileUtils.deleteDirectory(parentDirLocation);
   
 }

你可以嘗試如下

  File dir = new File("path");
   if (dir.isDirectory())
   {
         dir.delete();
   }

如果您的文件夾中有子文件夾,您可能需要遞歸刪除它們。

private void deleteFileOrFolder(File file){
    try {
        for (File f : file.listFiles()) {
            f.delete();
            deleteFileOrFolder(f);
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}
        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();
        }

    }

像魅力一樣工作。 對於文件夾和文件。 薩拉姆 :)

您也可以使用它來刪除包含子文件夾和文件的文件夾。

  1. 拳頭,創建一個遞歸函數。

     private void recursiveDelete(File file){ if(file.list().length > 0){ String[] list = file.list(); for(String is: list){ File currentFile = new File(file.getPath(),is); if(currentFile.isDirectory()){ recursiveDelete(currentFile); }else{ currentFile.delete(); } } }else { file.delete(); } }
  2. 然后,從您的初始函數使用 while 循環來調用遞歸。

     private boolean deleteFolderContainingSubFoldersAndFiles(){ boolean deleted = false; File folderToDelete = new File("C:/mainFolderDirectoryHere"); while(folderToDelete != null && folderToDelete.isDirectory()){ recursiveDelete(folderToDelete); } return deleted; }

這是一個簡單的方法:

public void deleteDirectory(String directoryPath)  {
      new Thread(new Runnable() {
          public void run() {
             for(String e: new File(directoryPath).list()) {
                 if(new File(e).isDirectory()) 
                     deleteDirectory(e);
                 else 
                     new File(e).delete();
             }
          }
      }).start();
  }
List<File> temp = Arrays.asList(new File("./DIRECTORY").listFiles());
for (int i = 0; i < temp.size(); i++)
{
    temp.get(i).delete();
}

從其他部分刪除它

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

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

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

也適用於子目錄。

import java.io.File;

public class Main{
   public static void main(String[] args) throws Exception {
      deleteDir(new File("c:\\temp"));
   }
   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();
      System.out.println("The directory is deleted.");
   }
}

你可以使用這個功能

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM