1 package net.sourceforge.importscrubber; 2 3 import java.io.File ; 4 import java.io.IOException ; 5 import java.util.*; 6 7 13 public class FileChooser implements Iterator 14 { 15 private String _sourceRoot, _classRoot; 16 private boolean _recurse; 17 int relStart; 19 20 private LinkedList possibles = new LinkedList(); 21 private FilePair nextFp; 22 23 public FileChooser(String sourceRoot, String classRoot, boolean recurse) throws IOException 24 { 25 File file = new File (sourceRoot); 26 if (!file.exists()) 27 throw new IllegalArgumentException (Resources.ERR_DIR_NOT_EXIST); 28 _sourceRoot = file.getCanonicalPath(); 29 30 file = new File (classRoot); 31 if (!file.isDirectory()) 32 throw new IllegalArgumentException (Resources.ERR_NOT_DIR); 33 if (!file.exists()) 34 throw new IllegalArgumentException (Resources.ERR_DIR_NOT_EXIST); 35 _classRoot = file.getCanonicalPath(); 36 37 _recurse = recurse; 38 39 relStart = ImportScrubber.getDirectory(_sourceRoot).length(); 40 41 possibles.add(_sourceRoot); 42 } 43 44 public void remove 45 () 46 { 47 throw new UnsupportedOperationException (); 48 } 49 50 public boolean hasNext() 51 { 52 if (nextFp == null) { 53 try { 54 nextFp = (FilePair)next(); 55 } catch (NoSuchElementException e) {} 56 } 57 return nextFp != null; 58 } 59 60 public Object next() throws NoSuchElementException 61 { 62 if (nextFp != null) { 63 FilePair f = nextFp; 64 nextFp = null; 65 return f; 66 } 67 68 FilePair fp = null; 69 while (fp == null) { 70 fp = nextPossible(); 71 } 72 return fp; 73 } 74 75 private FilePair nextPossible() throws NoSuchElementException 77 { 78 String s = (String )possibles.removeFirst(); 79 File tmp = new File (s); 80 if (tmp.isDirectory()) { 81 if (_recurse) { 82 String [] entries = tmp.list(new JavaFileFilter()); 83 for (int i = 0; i < entries.length; i++) { 84 possibles.add(s + ImportScrubber.FILE_SEPARATOR + entries[i]); 85 } 86 } 87 return nextPossible(); 88 } else { 89 return getPair(tmp); 90 } 91 } 92 93 private FilePair getPair(File source) 94 { 95 if (!(source.canRead() && source.canWrite())) { 96 return null; 97 } 98 String relativeSourceFilename = source.getParent().substring(relStart); 99 100 String cfilename = source.getName().substring(0, source.getName().length() - 5) + ".class"; 101 String classfilename = _classRoot + relativeSourceFilename + ImportScrubber.FILE_SEPARATOR + cfilename; 102 File classfile = new File (classfilename); 103 if(classfile.exists()) { 104 return new FilePair(source, classfile); 105 } 106 107 return null; 108 } 109 } 110 | Popular Tags |