public class LineIterator extends Object implements Iterator<String>
Reader
.
LineIterator
holds a reference to an open Reader
.
When you have finished with the iterator you should close the reader
to free internal resources. This can be done by closing the reader directly,
or by calling the close()
or closeQuietly(LineIterator)
method on the iterator.
The recommended usage pattern is:
LineIterator it = FileUtils.lineIterator(file, "UTF-8"); try { while (it.hasNext()) { String line = it.nextLine(); // do something with line } } finally { it.close(); }
Constructor and Description |
---|
LineIterator(Reader reader)
Constructs an iterator of the lines for a
Reader . |
Modifier and Type | Method and Description |
---|---|
void |
close()
Closes the underlying
Reader quietly. |
static void |
closeQuietly(LineIterator iterator)
Closes the iterator, handling null and ignoring exceptions.
|
boolean |
hasNext()
Indicates whether the
Reader has more lines. |
protected boolean |
isValidLine(String line)
Overridable method to validate each line that is returned.
|
String |
next()
Returns the next line in the wrapped
Reader . |
String |
nextLine()
Returns the next line in the wrapped
Reader . |
void |
remove()
Unsupported.
|
public LineIterator(Reader reader) throws IllegalArgumentException
Reader
.reader
- the Reader
to read from, not nullIllegalArgumentException
- if the reader is nullpublic boolean hasNext()
Reader
has more lines.
If there is an IOException
then close()
will
be called on this instance.hasNext
in interface Iterator<String>
true
if the Reader has more linesIllegalStateException
- if an IO exception occursprotected boolean isValidLine(String line)
line
- the line that is to be validatedpublic String next()
Reader
.next
in interface Iterator<String>
NoSuchElementException
- if there is no line to returnpublic String nextLine()
Reader
.NoSuchElementException
- if there is no line to returnpublic void close()
Reader
quietly.
This method is useful if you only want to process the first few
lines of a larger file. If you do not close the iterator
then the Reader
remains open.
This method can safely be called multiple times.public void remove()
remove
in interface Iterator<String>
UnsupportedOperationException
- alwayspublic static void closeQuietly(LineIterator iterator)
iterator
- the iterator to closeCopyright © 2002–2016 The Apache Software Foundation. All rights reserved.