initial commit
[scannotation] / src / main / java / org / scannotation / classpath / JarIterator.java
1 package org.scannotation.classpath;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.util.jar.JarEntry;
8 import java.util.jar.JarInputStream;
9
10 /**
11  * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
12  * @version $Revision: 1 $
13  */
14 public class JarIterator implements StreamIterator
15 {
16    JarInputStream jar;
17    JarEntry next;
18    Filter filter;
19    boolean initial = true;
20    boolean closed = false;
21
22    public JarIterator(File file, Filter filter) throws IOException
23    {
24       this(new FileInputStream(file), filter);
25    }
26
27
28    public JarIterator(InputStream is, Filter filter) throws IOException
29    {
30       this.filter = filter;
31       jar = new JarInputStream(is);
32    }
33
34    private void setNext()
35    {
36       initial = true;
37       try
38       {
39          if (next != null) jar.closeEntry();
40          next = null;
41          do
42          {
43             next = jar.getNextJarEntry();
44          } while (next != null && (next.isDirectory() || (filter == null || !filter.accepts(next.getName()))));
45          if (next == null)
46          {
47             close();
48          }
49       }
50       catch (IOException e)
51       {
52          throw new RuntimeException("failed to browse jar", e);
53       }
54    }
55
56    public InputStream next()
57    {
58       if (closed || (next == null && !initial)) return null;
59       setNext();
60       if (next == null) return null;
61       return new InputStreamWrapper(jar);
62    }
63
64    public void close()
65    {
66       try
67       {
68          closed = true;
69          jar.close();
70       }
71       catch (IOException ignored)
72       {
73
74       }
75
76    }
77 }