1 22 23 24 package com.mchange.v2.io; 25 26 import java.io.*; 27 import java.util.*; 28 29 public final class DirectoryDescentUtils 30 { 31 34 public static FileIterator depthFirstEagerDescent(File root) 35 throws IOException 36 { return depthFirstEagerDescent( root, null, false ); } 37 38 44 public static FileIterator depthFirstEagerDescent(File root, 45 FileFilter filter, 46 boolean canonical) 47 throws IOException 48 { 49 List list = new LinkedList(); 50 Set seenDirex = new HashSet(); 51 depthFirstEagerDescend(root, filter, canonical, list, seenDirex); 52 return new IteratorFileIterator( list.iterator() ); 53 } 54 55 public static void addSubtree( File root, FileFilter filter, boolean canonical, Collection addToMe ) throws IOException 56 { 57 Set seenDirex = new HashSet(); 58 depthFirstEagerDescend(root, filter, canonical, addToMe, seenDirex); 59 } 60 61 private static void depthFirstEagerDescend(File dir, FileFilter filter, boolean canonical, 62 Collection addToMe, Set seenDirex) 63 throws IOException 64 { 65 String canonicalPath = dir.getCanonicalPath(); 66 if (! seenDirex.contains( canonicalPath ) ) 67 { 68 if ( filter == null || filter.accept( dir ) ) 69 addToMe.add( canonical ? new File( canonicalPath ) : dir ); 70 seenDirex.add( canonicalPath ); 71 String [] babies = dir.list(); 72 for (int i = 0, len = babies.length; i < len; ++i) 73 { 74 File baby = new File(dir, babies[i]); 75 if (baby.isDirectory()) 76 depthFirstEagerDescend(baby, filter, canonical, addToMe, seenDirex); 77 else 78 if ( filter == null || filter.accept( baby ) ) 79 addToMe.add( canonical ? baby.getCanonicalFile() : baby ); 80 } 81 } 82 } 83 84 private static class IteratorFileIterator implements FileIterator 85 { 86 Iterator ii; 87 Object last; 88 89 IteratorFileIterator(Iterator ii) 90 { this.ii = ii; } 91 92 public File nextFile() throws IOException 93 { return (File) next(); } 94 95 public boolean hasNext() throws IOException 96 { return ii.hasNext(); } 97 98 public Object next() throws IOException 99 { return (last = ii.next()); } 100 101 public void remove() throws IOException 102 { 103 if (last != null) 104 { 105 ((File) last).delete(); 106 last = null; 107 } 108 else 109 throw new IllegalStateException (); 110 } 111 112 public void close() throws IOException 113 {} 114 } 115 116 private DirectoryDescentUtils() 117 {} 118 119 public static void main(String [] argv) 120 { 121 try 122 { 123 FileIterator fii = depthFirstEagerDescent( new File(argv[0]) ); 124 while (fii.hasNext()) 125 System.err.println( fii.nextFile().getPath() ); 126 } 127 catch (Exception e) 128 { e.printStackTrace(); } 129 } 130 } 131 | Popular Tags |