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  		catch (IOException e) {
    41      		throw new IllegalStateException(e);
    42  		}
    43  	}
    44
    45  	public Iterator<String> iterator() {
    46  		return new FileIterator();
    47  	}
    48
    49  	class FileIterator implements Iterator<String> {
    50
    51  		private boolean hasNext = true;
    52
    53  		public boolean hasNext() {
    54  			return hasNext;
    55  		}
    56
    57  		public String next() {
    58  			String line = null;
    59  			try {
    60  				if ( hasNext ) {
    61  					line = lineReader.readLine();
    62  					if ( line == null ) {
    63  						hasNext = false;
    64  						line = "";
    65  					}
    66  				}
    67  				return line;
    68  			} catch (IOException e) {
    69  				throw new IllegalStateException(e);
    70  			}
    71  		}
    72
    73  		public void remove() {
    74  			throw new UnsupportedOperationException("remove is not supported by " + this.getClass().getName());
    75  		}
    76
    77  	}
    78
    79  }