1 package net.sf.openrocket.file;
4 import java.io.FileFilter;
5 import java.io.IOException;
6 import java.io.InputStream;
8 import java.util.Iterator;
9 import java.util.NoSuchElementException;
11 import net.sf.openrocket.logging.LogHelper;
12 import net.sf.openrocket.startup.Application;
13 import net.sf.openrocket.util.JarUtil;
14 import net.sf.openrocket.util.Pair;
16 public abstract class DirectoryIterator implements Iterator<Pair<String, InputStream>> {
18 private static final LogHelper logger = Application.getLogger();
20 private Pair<String, InputStream> next = null;
23 public boolean hasNext() {
28 return (next != null);
33 public Pair<String, InputStream> next() {
38 throw new NoSuchElementException("No more files");
41 Pair<String, InputStream> n = next;
48 public void remove() {
49 throw new UnsupportedOperationException("remove() not supported");
55 * Closes the resources related to this iterator. This method should be
56 * overridden if the iterator needs to close any resources of its own, but
57 * must call this method as well.
63 } catch (IOException e) {
64 logger.error("Error closing file " + next.getU());
71 * Return the next pair of file name and InputStream.
73 * @return a pair with the file name and input stream reading the file.
75 protected abstract Pair<String, InputStream> findNext();
80 * Return a DirectoryIterator for a directory that can be located either
81 * within the containing JAR file, in the classpath or in the current directory
82 * (searched in this order). The first place that contains matching files
83 * will be iterated through.
85 * @param directory the directory to search for.
86 * @param filter the filter for matching files in the directory.
87 * @return a DirectoryIterator for iterating through the files in the
88 * directory, or <code>null</code> if no directory containing
89 * matching files can be found.
91 public static DirectoryIterator findDirectory(String directory, FileFilter filter) {
92 DirectoryIterator iterator = null;
94 // Try to load from containing JAR file
95 File jarFile = JarUtil.getCurrentJarFile();
96 if (jarFile != null) {
98 iterator = new ZipDirectoryIterator(jarFile, directory, filter);
99 if (iterator.hasNext()) {
103 } catch (IOException e) {
104 logger.error("Error opening containing JAR file " + jarFile, e);
109 // Try to find directory as a system resource
110 URL url = ClassLoader.getSystemResource(directory);
113 File dir = JarUtil.urlToFile(url);
114 iterator = new RegularDirectoryIterator(dir, filter);
115 if (iterator.hasNext()) {
119 } catch (Exception e1) {
120 logger.error("Error opening directory from URL " + url);
125 // Try to open directory as such
127 iterator = new RegularDirectoryIterator(new File(directory), filter);
128 if (iterator.hasNext()) {
132 } catch (IOException e) {
133 logger.error("Error opening directory " + directory);