Revision created by MOE tool push_codebase.
[gae.git] / java / src / main / com / google / appengine / tools / util / FileIterator.java
blobf1e393a0ea5bd9a5b9c5d497499d9ab9c394fa98
1 // Copyright 2009, Google Inc. All rights reserved.
3 package com.google.appengine.tools.util;
5 import java.io.File;
6 import java.util.Arrays;
7 import java.util.Iterator;
8 import java.util.LinkedList;
9 import java.util.NoSuchElementException;
11 /**
12 * Walks a directory tree, returning all the files.
16 public class FileIterator implements Iterator<File>, Iterable<File> {
17 private LinkedList<File> dirs = new LinkedList<File>();
18 private Iterator<File> files;
19 private File next;
21 public FileIterator(File base) {
22 File[] baseFiles = base.listFiles();
23 if (baseFiles != null) {
24 files = Arrays.asList(baseFiles).iterator();
26 _next();
29 @Override
30 public boolean hasNext() {
31 return next != null;
34 @Override
35 public File next() {
36 if (next == null) {
37 throw new NoSuchElementException();
39 return _next();
42 private File _next() {
43 File result = next;
44 next = null;
45 while (files != null) {
46 try {
47 File f = files.next();
48 if (f.isDirectory()) {
49 dirs.add(f);
50 } else {
51 next = f;
52 break;
54 } catch (NoSuchElementException ex) {
55 if (dirs.isEmpty())
56 files = null;
57 else
58 files = Arrays.asList(dirs.removeFirst().listFiles()).iterator();
61 return result;
64 @Override
65 public void remove() {
66 throw new UnsupportedOperationException();
69 public Iterator<File> iterator() {
70 return this;