View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.util;
5   
6   import java.io.File;
7   import java.io.FileNotFoundException;
8   import java.io.FileReader;
9   import java.io.IOException;
10  import java.io.LineNumberReader;
11  import java.util.Iterator;
12  
13  /**
14   *
15   * <p>Handy class to easily iterate over a file, line by line, using
16   * a Java 5 for loop.</p>
17   *
18   * @author Romain Pelisse <belaran@gmail.com>
19   *
20   */
21  public class FileIterable implements Iterable<String> {
22  
23  	private  LineNumberReader lineReader = null;
24  
25  	public FileIterable(File file) {
26  
27       	try {
28      		lineReader = new LineNumberReader( new FileReader(file) );
29      	}
30      	catch (FileNotFoundException e) {
31      		throw new IllegalStateException(e);
32      	}
33  	}
34  
35  	protected void finalize() throws Throwable {
36  		try {
37  			if (lineReader!= null) {
38  				lineReader.close();
39  			}
40  		}
41  		catch (IOException e) {
42      		throw new IllegalStateException(e);
43  		}
44  		super.finalize();
45  	}
46  
47  	public Iterator<String> iterator() {
48  		return new FileIterator();
49  	}
50  
51  	class FileIterator implements Iterator<String> {
52  
53  		private boolean hasNext = true;
54  
55  		public boolean hasNext() {
56  			return hasNext;
57  		}
58  
59  		public String next() {
60  			String line = null;
61  			try {
62  				if ( hasNext ) {
63  					line = lineReader.readLine();
64  					if ( line == null ) {
65  						hasNext = false;
66  						line = "";
67  					}
68  				}
69  				return line;
70  			} catch (IOException e) {
71  				throw new IllegalStateException(e);
72  			}
73  		}
74  
75  		public void remove() {
76  			throw new UnsupportedOperationException("remove is not supported by " + this.getClass().getName());
77  		}
78  
79  	}
80  
81  }