Class FileLineIterator

java.lang.Object
FileLineIterator
All Implemented Interfaces:
Iterator<String>

public class FileLineIterator
extends Object
implements Iterator<String>
FileLineIterator 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. See Java's documentation for BufferedReader to learn how to construct one given a path to a file. Then, think about how you can use BufferedReader's methods within this class to implement our desired functionality.

Note: Any IOExceptions thrown by readers should be caught and handled properly.

  • Constructor Details

    • FileLineIterator

      public FileLineIterator​(String filePath)
      Creates a FileLineIterator for the file located at filePath. Fill out the constructor so that a user can instantiate a FileLineIterator. 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 or FileReader, then hasNext should return false.

      Parameters:
      filePath - - the path to the CSV file to be turned to an Iterator
      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 should close the BuffereReader.

      Specified by:
      hasNext in interface Iterator<String>
      Returns:
      a boolean indicating whether the FileLineIterator can produce another line from the file
    • next

      public String 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, the next time next() is called, it should throw a NoSuchElementException.

      Specified by:
      next in interface Iterator<String>
      Returns:
      the next line in the file
      Throws:
      NoSuchElementException - if there is no more data in the file