1 package net.sf.openrocket.file;
4 import java.io.FileFilter;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.util.Enumeration;
8 import java.util.zip.ZipEntry;
9 import java.util.zip.ZipFile;
11 import net.sf.openrocket.logging.LogHelper;
12 import net.sf.openrocket.startup.Application;
13 import net.sf.openrocket.util.Pair;
16 * A DirectoryIterator that reads files from the specified directory of a
19 * TODO: MEDIUM: This is always a recursive search.
21 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
23 public class ZipDirectoryIterator extends DirectoryIterator {
25 private static final LogHelper logger = Application.getLogger();
27 private final File zipFileName;
28 private final String directory;
29 private final FileFilter filter;
31 private ZipFile zipFile;
32 private Enumeration<? extends ZipEntry> entries;
38 * @param zipFileName the ZIP file to read.
39 * @param directory the directory within the ZIP file to read, relative to the
40 * base (an empty string corresponds to the root directory)
41 * @param filter the filter for accepted files.
42 * @throws IOException if the ZIP file could not be read.
44 public ZipDirectoryIterator(File zipFileName, String directory, FileFilter filter)
47 // Process directory and extension
48 if (!directory.endsWith("/")) {
52 this.zipFileName = zipFileName;
53 this.directory = directory;
57 // Loop through ZIP entries searching for files to load
58 this.zipFile = new ZipFile(zipFileName);
59 entries = zipFile.entries();
67 if (zipFile != null) {
70 } catch (IOException e) {
71 logger.error("Closing ZIP file failed", e);
80 protected Pair<String, InputStream> findNext() {
81 if (entries == null) {
85 while (entries.hasMoreElements()) {
86 ZipEntry entry = entries.nextElement();
87 String name = entry.getName();
88 File file = new File(name);
89 if (name.startsWith(directory) && filter.accept(file)) {
91 InputStream is = zipFile.getInputStream(entry);
92 return new Pair<String, InputStream>(name, is);
93 } catch (IOException e) {
94 logger.error("IOException when reading ZIP file " + zipFileName, e);
99 // No more elements exist