forked from pmd/pmd
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a handy class to iterate over a file, line by line (to be used in…
… unit test, while checking result file)
- Loading branch information
Showing
1 changed file
with
79 additions
and
0 deletions.
There are no files selected for viewing
79 changes: 79 additions & 0 deletions
79
pmd/src/main/java/net/sourceforge/pmd/util/FileIterable.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
/** | ||
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html | ||
*/ | ||
package net.sourceforge.pmd.util; | ||
|
||
import java.io.File; | ||
import java.io.FileNotFoundException; | ||
import java.io.FileReader; | ||
import java.io.IOException; | ||
import java.io.LineNumberReader; | ||
import java.util.Iterator; | ||
|
||
/** | ||
* | ||
* <p>Handy class to easily iterate over a file, line by line, using | ||
* a Java 5 for loop.</p> | ||
* | ||
* @author Romain Pelisse <belaran@gmail.com> | ||
* | ||
*/ | ||
public class FileIterable implements Iterable<String> { | ||
|
||
private LineNumberReader lineReader = null; | ||
|
||
public FileIterable(File file) { | ||
|
||
try { | ||
lineReader = new LineNumberReader( new FileReader(file) ); | ||
} | ||
catch (FileNotFoundException e) { | ||
throw new IllegalStateException(e); | ||
} | ||
} | ||
|
||
protected void finalize() throws Throwable { | ||
try { | ||
if (lineReader!= null) | ||
lineReader.close(); | ||
} | ||
catch (IOException e) { | ||
throw new IllegalStateException(e); | ||
} | ||
} | ||
|
||
public Iterator<String> iterator() { | ||
return new FileIterator(); | ||
} | ||
|
||
class FileIterator implements Iterator<String> { | ||
|
||
private boolean hasNext = true; | ||
|
||
public boolean hasNext() { | ||
return hasNext; | ||
} | ||
|
||
public String next() { | ||
String line = null; | ||
try { | ||
if ( hasNext ) { | ||
line = lineReader.readLine(); | ||
if ( line == null ) { | ||
hasNext = false; | ||
line = ""; | ||
} | ||
} | ||
return line; | ||
} catch (IOException e) { | ||
throw new IllegalStateException(e); | ||
} | ||
} | ||
|
||
public void remove() { | ||
throw new UnsupportedOperationException("remove is not supported by " + this.getClass().getName()); | ||
} | ||
|
||
} | ||
|
||
} |