廣告

2015年1月29日 星期四

[java] delete non-empty folder / (subfolders). | 刪除整個文件(包含裡面的文件)

以下提供兩種刪整個非空資料夾的方法,
但實際翻了一下
FileUtils.deleteDirectory(File folder);
的source code 後發現兩種是一樣的=.=...

另外:
FileUtils.waitFor(file, 5);
是個好用的東西,他實際上就是在時間內
一直呼叫file.exist(),並且程式會停在這邊,
直到時間到.
這樣就不用自己寫監控檔案下載完了沒XD

package test_fb_api;
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

//http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#deleteDirectory%28java.io.File%29

public class testDeleteNonEmptyFolder {

 public static int tag = 0;

 public static void main(String[] args) {

  String path = "F:/opt_test/";
  String path2 = "F:/opt_test2/";

  File file = new File(path);

  System.out.println(FileUtils.waitFor(file, 5));

  System.out.println("deleteMethodB:");
  System.out.println("exists before delete : " + file.exists());
  deleteMethodB(file);
  System.out.println("exists after  delete : " + file.exists());

  System.out.println("===========================");
  System.out.println("deleteMethodA:");
  File file2 = new File(path2);
  // set tag = 0 , because "deleteMethodA" is recursive.
  // so you don't know where go false, or is still folder
  tag = 0;
  System.out.println("exists before delete : " + file2.exists());
  deleteMethodA(file2);
  if (tag == 0) {
   System.out.println("deleteMethodA: delete success");
  } else {
   System.out.println("deleteMethodA: have subFolder: " + tag);
  }
  System.out.println("exists after  delete : " + file2.exists());
 }

 public static void deleteMethodB(File folder) {
  try {
   FileUtils.deleteDirectory(folder);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   System.out.println(e.getMessage());
  }
 }

 public static void deleteMethodA(File folder) {
  // check if folder file is a real folder
  if (folder.isDirectory()) {
   File[] list = folder.listFiles();
   if (list != null) {
    for (int i = 0; i < list.length; i++) {
     File tmpF = list[i];
     if (tmpF.isDirectory()) {
      deleteMethodA(tmpF);
     }
     if (!tmpF.delete()) {
      tag++;
     }
    }
   }
   if (!folder.delete()) {
    System.out.println("can't delete folder : " + folder);
   }
  }
 }

}



沒有留言:

張貼留言