欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java刪除文件、目錄及目錄下所有文件的方法實(shí)例

 更新時(shí)間:2016年12月26日 09:18:27   作者:上品物語(yǔ)  
這篇文章主要給大家介紹了關(guān)于利用Java刪除文件、目錄及目錄下所有文件的方法,文中給出了詳細(xì)的示例代碼與注解,有需要的朋友可以參考借鑒,下面來(lái)一起看看吧。

前言

本文主要實(shí)現(xiàn)的功能是刪除某個(gè)目錄及目錄下的所有子目錄和文件,涉及到的知識(shí)點(diǎn):File.delete()用于刪除“某個(gè)文件或者空目錄”!所以要?jiǎng)h除某個(gè)目錄及其中的所有文件和子目錄,要進(jìn)行遞歸刪除。

具體代碼示例如下:

import java.io.File;

public class DeleteDirectory {
 /**
 * 刪除空目錄
 * @param dir 將要?jiǎng)h除的目錄路徑
 */
 private static void doDeleteEmptyDir(String dir) {
 boolean success = (new File(dir)).delete();
 if (success) {
  System.out.println("Successfully deleted empty directory: " + dir);
 } else {
  System.out.println("Failed to delete empty directory: " + dir);
 }
 }

 /**
 * 遞歸刪除目錄下的所有文件及子目錄下所有文件
 * @param dir 將要?jiǎng)h除的文件目錄
 * @return boolean Returns "true" if all deletions were successful.
 *   If a deletion fails, the method stops attempting to
 *   delete and returns "false".
 */
 private 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;
  }
  }
 }
 // 目錄此時(shí)為空,可以刪除
 return dir.delete();
 }
 /**
 *測(cè)試
 */
 public static void main(String[] args) {
 doDeleteEmptyDir("new_dir1");
 String newDir2 = "new_dir2";
 boolean success = deleteDir(new File(newDir2));
 if (success) {
  System.out.println("Successfully deleted populated directory: " + newDir2);
 } else {
  System.out.println("Failed to delete populated directory: " + newDir2);
 } 
 }
}

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流。

相關(guān)文章

最新評(píng)論