Class LineIterator
LineIterator
provides a useful wrapper around Java's provided
BufferedReader
and provides practice with implementing an Iterator
. Your
solution should not read the entire file into memory at once, instead reading
a line whenever the next()
method is called.
Notes:
- Any IOExceptions
thrown be caught and handled properly.
- Do not use the ready()
method from BufferedReader
.
-
Constructor Summary
ConstructorsConstructorDescriptionLineIterator
(BufferedReader reader) Constructs aLineIterator
for reader.LineIterator
(String filePath) Creates a LineIterator from a provided filePath by creating a FileReader and BufferedReader for the file. -
Method Summary
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface java.util.Iterator
forEachRemaining, remove
-
Constructor Details
-
LineIterator
Constructs aLineIterator
for reader. Feel free to create and instantiate any variables that your implementation requires here. See recitation and lecture notes for guidance.If an IOException is thrown by the BufferedReader, then hasNext should return false.
The only method that should be called on BufferedReader is readLine() and close(). You cannot call any other methods.
- Parameters:
reader
- - A reader to be turned to an Iterator- Throws:
IllegalArgumentException
- if reader is null
-
LineIterator
Creates a LineIterator from a provided filePath by creating a FileReader and BufferedReader for the file.This constructor is implemented for you. DO NOT MODIFY THIS CONSTRUCTOR.
- Parameters:
filePath
- - a string representing the file- Throws:
IllegalArgumentException
- if filePath is null or if the file doesn't exist
-
-
Method Details
-
hasNext
public boolean hasNext()Returns true if there are lines left to read in the file, and false otherwise.If there are no more lines left, this method attempts to close the BufferedReader. In case of an IOException during the closing process, an error message is printed to the console indicating the issue.
-
next
Returns the next line from the file, or throws a NoSuchElementException if there are no more strings left to return (i.e. hasNext() is false).This method also advances the iterator in preparation for another invocation. If an IOException is thrown during a next() call, your iterator should make note of this such that future calls of hasNext() will return false and future calls of next() will throw a NoSuchElementException
- Specified by:
next
in interfaceIterator<String>
- Returns:
- the next line in the file
- Throws:
NoSuchElementException
- if there is no more data in the file
-