A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Piaget 中级黑马   /  2015-2-9 21:27  /  1426 人查看  /  10 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 Piaget 于 2015-2-24 13:24 编辑

  1. <div class="blockcode"><blockquote>import java.io.File;

  2. public class TestDigui
  3. {
  4.         /**
  5.          * 删除多级文件
  6.          */
  7.         public static void main(String[] args)
  8.         {
  9.                 deleDir("F:\\java");
  10.         }

  11.         public static void deleDir(String path)
  12.         {
  13.                 File file = new File(path);
  14.                 String[] names = file.list();
  15.                 for (String string : names)
  16.                 {

  17.                         System.out.println(string);
  18.                         String newpath = path + "\\" + string;
  19.                         File newFile = new File(newpath);
  20.                         if (newFile.isDirectory())
  21.                         {
  22.                                 deleDir(newFile.getPath());
  23.                         }
  24. //                        newFile.delete();//删除文件
  25.                        
  26.                 }
  27.         }
  28. }
复制代码

注释的部分是第一次写的时候没考虑周到,发现删除完剩余了多级空文件夹。分析发现,如果有else,当一个文件夹是空的,递归一下,下次得不到里面的内容,也就不能进入遍历。于是if操作结束,但是不会进入else。最后删除不了这个空文件夹。
而去掉else,当这个文件夹是空的,结束if语句会向下执行删除操作。空文件夹就删除了。

10 个回复

倒序浏览
:):):):):)
回复 使用道具 举报
1,这个应该有个FileNotFoundExpection
2, 遍历出来的String是个绝对路径,递归体的中调用自身出错.
回复 使用道具 举报
边晓炎 来自手机 中级黑马 2015-2-10 00:25:49
板凳
没看到删除!出现空文件夹的情况只需要你在递归后file.delete就删除了!

点评

哦哦!怎么感觉你贴上去的代码不对劲!  发表于 2015-2-11 14:41
代码显示不完全。多谢提醒。  发表于 2015-2-11 00:45
回复 使用道具 举报
huangchunwei 来自手机 中级黑马 2015-2-10 09:37:47
报纸
学习了。。。:):):)
回复 使用道具 举报
cly成子 来自手机 中级黑马 2015-2-10 09:49:13
地板
有点深!待学习!受教了!
回复 使用道具 举报
瞿乐 中级黑马 2015-2-10 11:11:18
7#
本帖最后由 瞿乐 于 2015-2-10 11:27 编辑

我这里有个逻辑看起来简单些的。
  1.         public static void deleDir(File file){
  2.                 final File[] fs = file.listFiles();
  3.                
  4.                 if(file.isFile()||fs==null||fs.length==0){
  5.                         System.out.println("del::"+file.getAbsolutePath());
  6.                         file.delete();
  7.                 }else{
  8.                         for(File f: fs){
  9.                                 deleDir(f);
  10.                                 System.out.println(f.getAbsolutePath());
  11.                                 f.delete();
  12.                         }
  13.                 }
  14.         }
复制代码
但是还有个bug。
回复 使用道具 举报
瞿乐 中级黑马 2015-2-10 11:26:51
8#
瞿乐 发表于 2015-2-10 11:11
我这里有个逻辑看起来简单些的。

但是还有个bug。
回复 使用道具 举报
顶你,给哦黑马币
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马