src/share/classes/java/util/zip/ZipFile.java
Print this page
@@ -29,10 +29,11 @@
import java.io.InputStream;
import java.io.IOException;
import java.io.EOFException;
import java.io.File;
import java.nio.charset.Charset;
+import java.util.Iterator;
import java.util.Vector;
import java.util.Enumeration;
import java.util.Set;
import java.util.HashSet;
import java.util.NoSuchElementException;
@@ -48,11 +49,11 @@
* thrown.
*
* @author David Connelly
*/
public
-class ZipFile implements ZipConstants, Closeable {
+class ZipFile implements ZipConstants, Closeable, Iterable<ZipEntry> {
private long jzfile; // address of jzfile data
private String name; // zip file name
private int total; // total number of entries
private boolean closeRequested;
@@ -446,44 +447,77 @@
public Enumeration<? extends ZipEntry> entries() {
ensureOpen();
return new Enumeration<ZipEntry>() {
private int i = 0;
public boolean hasMoreElements() {
- synchronized (ZipFile.this) {
+ return hasNextEntry(i);
+ }
+ public ZipEntry nextElement() throws NoSuchElementException {
+ return nextEntry(i++);
+ }
+ };
+ }
+
+ /**
+ * Returns an iterator over the entries in this ZIP file.
+ *
+ * @return an iterator over the entries in this ZIP file.
+ *
+ * @throws IllegalStateException if the zip file has been closed
+ */
+
+ public Iterator<ZipEntry> iterator() {
ensureOpen();
+ return new Iterator<ZipEntry>() {
+ private int i = 0;
+
+ public boolean hasNext() {
+ return hasNextEntry(i);
+ }
+ public ZipEntry next() {
+ return nextEntry(i++);
+ }
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
+
+ private boolean hasNextEntry(int i) {
+ synchronized (this) {
+ ensureOpen();
return i < total;
}
}
- public ZipEntry nextElement() throws NoSuchElementException {
- synchronized (ZipFile.this) {
+
+ private ZipEntry nextEntry(int i) {
+ synchronized (this) {
ensureOpen();
if (i >= total) {
throw new NoSuchElementException();
}
- long jzentry = getNextEntry(jzfile, i++);
+ long jzentry = getNextEntry(jzfile, i);
if (jzentry == 0) {
String message;
if (closeRequested) {
message = "ZipFile concurrently closed";
} else {
- message = getZipMessage(ZipFile.this.jzfile);
+ message = getZipMessage(jzfile);
}
throw new ZipError("jzentry == 0" +
- ",\n jzfile = " + ZipFile.this.jzfile +
- ",\n total = " + ZipFile.this.total +
- ",\n name = " + ZipFile.this.name +
+ ",\n jzfile = " + jzfile +
+ ",\n total = " + total +
+ ",\n name = " + name +
",\n i = " + i +
",\n message = " + message
);
}
ZipEntry ze = getZipEntry(null, jzentry);
freeEntry(jzfile, jzentry);
return ze;
}
}
- };
- }
private ZipEntry getZipEntry(String name, long jzentry) {
ZipEntry e = new ZipEntry();
e.flag = getEntryFlag(jzentry); // get the flag first
if (name != null) {