Class LineIterator

  • All Implemented Interfaces:
    Closeable, AutoCloseable, Iterator<String>

    public class LineIterator
    extends Object
    implements Iterator<String>, Closeable
    An Iterator over the lines in a 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();
     }
     
    Since:
    1.2
    • Method Detail

      • hasNext

        public boolean hasNext()
        Indicates whether the Reader has more lines. If there is an IOException then close() will be called on this instance.
        Specified by:
        hasNext in interface Iterator<String>
        Returns:
        true if the Reader has more lines
        Throws:
        IllegalStateException - if an IO exception occurs
      • nextLine

        public String nextLine()
        Returns the next line in the wrapped Reader.
        Returns:
        the next line from the input
        Throws:
        NoSuchElementException - if there is no line to return
      • close

        public void close()
                   throws IOException
        Closes the underlying 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.
        Specified by:
        close in interface AutoCloseable
        Specified by:
        close in interface Closeable
        Throws:
        IOException - if closing the underlying Reader fails.
      • closeQuietly

        @Deprecated
        public 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.
        Closes a LineIterator quietly.
        Parameters:
        iterator - The iterator to close, or null.
        See Also:
        Throwable.addSuppressed(java.lang.Throwable)