public class LineIterator extends Object implements Iterator<String>, Closeable
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 . |
static void |
closeQuietly(LineIterator iterator)
Deprecated.
As of 2.6 deprecated without replacement. Please use the try-with-resources statement or handle
suppressed exceptions manually.
|
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.
|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
forEachRemaining
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() throws IOException
Reader
.
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.close
in interface Closeable
close
in interface AutoCloseable
IOException
- if closing the underlying Reader
fails.public void remove()
remove
in interface Iterator<String>
UnsupportedOperationException
- always@Deprecated public static void closeQuietly(LineIterator iterator)
LineIterator
quietly.iterator
- The iterator to close, or null
.Throwable.addSuppressed(java.lang.Throwable)
Copyright © 2002–2020 The Apache Software Foundation. All rights reserved.