1.0.3
[scannotation] / src / main / java / org / scannotation / archiveiterator / FileIterator.java
1 package org.scannotation.archiveiterator;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileNotFoundException;
6 import java.io.InputStream;
7 import java.util.ArrayList;
8 import java.util.List;
9
10 /**
11  * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
12  * @version $Revision: 1 $
13  */
14 public class FileIterator implements StreamIterator
15 {
16    private ArrayList files;
17    private int index = 0;
18
19    public FileIterator(File file, Filter filter)
20    {
21       files = new ArrayList();
22       try
23       {
24          create(files, file, filter);
25       }
26       catch (Exception e)
27       {
28          throw new RuntimeException(e);
29       }
30    }
31     protected static void create(List list, File dir, Filter filter) throws Exception
32     {
33         create(list, dir, filter, dir.getCanonicalPath());
34     }
35    protected static void create(List list, File dir, Filter filter, String prefix) throws Exception
36    {
37       File[] files = dir.listFiles();
38       for (int i = 0; i < files.length; i++)
39       {
40          if (files[i].isDirectory())
41          {
42             create(list, files[i], filter, prefix);
43          }
44          else
45          {
46              String path = files[i].getCanonicalPath();
47              String relativePath = path.substring(prefix.length() + 1);
48              if (File.separatorChar == '\\')
49                  relativePath = relativePath.replace('\\', '/');
50              if (filter == null || filter.accepts(relativePath))
51             {
52                list.add(files[i]);
53             }
54          }
55       }
56    }
57
58    public InputStream next()
59    {
60       if (index >= files.size()) return null;
61       File fp = (File) files.get(index++);
62       try
63       {
64          return new FileInputStream(fp);
65       }
66       catch (FileNotFoundException e)
67       {
68          throw new RuntimeException(e);
69       }
70    }
71
72    public void close()
73    {
74    }
75 }