删除一个非空目录,并显示所有被删除的文件和目录列表
第一个是递归程序,第二个用一个LinkedList模拟实现,(java)
程序一
1 package file;
2
3 import java.io.File;
4
5 public class Del {
6
7 /**
8 * @param args
9 */
10 public static void main(String[] args) {
11 // TODO Auto-generated method stub
12
13 if(args.length < 1)
14 {
15 System.out.println("pls input the dir which u like to delete ");
16 return;
17 }
18 Del d = new Del();
19 d.del("d:\\temp");
20
21
22 }
23
24 public void del(String dir)
25 {
26 File f;
27 File dirin = new File(dir);
28 String list[] = dirin.list();
29 for(String li:list)
30 {
31 f = new File(dir+"\\\\"+li);//之前没有考虑到的路径问题
32 if(f.isFile())
33 {
34 System.out.println("file deleted: "+ f.getAbsolutePath());
35 f.delete();
36 }
37 else if(f.isDirectory())
38 {
39 del(f.getAbsolutePath());
40 System.out.println("dir deleted: " + f.getName());
41 }
42 }
43 dirin.delete();
44 }
45
46 }
47
程序二
1 package file;
2
3 import java.io.File;
4 import java.util.LinkedList;
5
6 public class FromBookDel {
7 public void delete(File dir)
8 {
9 LinkedList dirs = new LinkedList();
10 dirs.addFirst(dir);
11
12 while(!dirs.isEmpty())
13 { boolean empty = true;
14 File c_dir = (File)dirs.getFirst();
15 File[] files = c_dir.listFiles();
16 if(files.length<=0)
17 {
18 System.out.println("dir deled: " + dir.getAbsolutePath());
19 dir.delete();
20 dirs.removeFirst();
21 }
22 for(File f: files)
23 {
24 if(f.isFile())
25 {
26 System.out.println("file deled: " + f.getAbsolutePath());
27 f.delete();
28 }
29 else
30 {
31 empty = false;
32 dirs.addFirst(f);
33 }
34 }
35 if(empty)
36 {
37 c_dir.delete();
38 dirs.removeFirst();
39 }
40 }
41
42 }
43
44 public static void main(String[]args)
45 {
46 FromBookDel del = new FromBookDel();
47 del.delete(new File("d:\\temp"));
48 }
49 }
50
posted on 2008-03-30 23:21
fullfocus 阅读(362)
评论(0) 编辑 收藏 所属分类:
算法