    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.io;
    018
    019import java.io.BufferedReader;
    020import java.io.Closeable;
    021import java.io.IOException;
    022import java.io.Reader;
    023import java.util.Iterator;
    024import java.util.NoSuchElementException;
    025
    026/**
    027 * An Iterator over the lines in a {@code Reader}.
    028 * <p>
    029 * {@code LineIterator} holds a reference to an open {@code Reader}.
    030 * When you have finished with the iterator you should close the reader
    031 * to free internal resources. This can be done by closing the reader directly,
    032 * or by calling the {@link #close()} or {@link #closeQuietly(LineIterator)}
    033 * method on the iterator.
    034 * <p>
    035 * The recommended usage pattern is:
    036 * <pre>
    037 * LineIterator it = FileUtils.lineIterator(file, "UTF-8");
    038 * try {
    039 *   while (it.hasNext()) {
    040 *     String line = it.nextLine();
    041 *     // do something with line
    042 *   }
    043 * } finally {
    044 *   it.close();
    045 * }
    046 * </pre>
    047 *
    048 * @since 1.2
    049 */
    050public class LineIterator implements Iterator<String>, Closeable {
    051
    052    // N.B. This class deliberately does not implement Iterable, see https://issues.apache.org/jira/browse/IO-181
    053
    054    /** The reader that is being read. */
    055    private final BufferedReader bufferedReader;
    056    /** The current line. */
    057    private String cachedLine;
    058    /** A flag indicating if the iterator has been fully read. */
    059    private boolean finished;
    060
    061    /**
    062     * Constructs an iterator of the lines for a {@code Reader}.
    063     *
    064     * @param reader the {@code Reader} to read from, not null
    065     * @throws IllegalArgumentException if the reader is null
    066     */
    067    public LineIterator(final Reader reader) throws IllegalArgumentException {
    068        if (reader == null) {
    069            throw new IllegalArgumentException("Reader must not be null");
    070        }
    071        if (reader instanceof BufferedReader) {
    072            bufferedReader = (BufferedReader) reader;
    073        } else {
    074            bufferedReader = new BufferedReader(reader);
    075        }
    076    }
    077
    078    //-----------------------------------------------------------------------
    079    /**
    080     * Indicates whether the {@code Reader} has more lines.
    081     * If there is an {@code IOException} then {@link #close()} will
    082     * be called on this instance.
    083     *
    084     * @return {@code true} if the Reader has more lines
    085     * @throws IllegalStateException if an IO exception occurs
    086     */
    087    @Override
    088    public boolean hasNext() {
    089        if (cachedLine != null) {
    090            return true;
    091        }
    092        if (finished) {
    093            return false;
    094        }
    095        try {
    096            while (true) {
    097                final String line = bufferedReader.readLine();
    098                if (line == null) {
    099                    finished = true;
    100                    return false;
    101                }
    102                if (isValidLine(line)) {
    103                    cachedLine = line;
    104                    return true;
    105                }
    106            }
    107        } catch(final IOException ioe) {
    108            IOUtils.closeQuietly(this, ioe::addSuppressed);
    109            throw new IllegalStateException(ioe);
    110        }
    111    }
    112
    113    /**
    114     * Overridable method to validate each line that is returned.
    115     * This implementation always returns true.
    116     * @param line  the line that is to be validated
    117     * @return true if valid, false to remove from the iterator
    118     */
    119    protected boolean isValidLine(final String line) {
    120        return true;
    121    }
    122
    123    /**
    124     * Returns the next line in the wrapped {@code Reader}.
    125     *
    126     * @return the next line from the input
    127     * @throws NoSuchElementException if there is no line to return
    128     */
    129    @Override
    130    public String next() {
    131        return nextLine();
    132    }
    133
    134    /**
    135     * Returns the next line in the wrapped {@code Reader}.
    136     *
    137     * @return the next line from the input
    138     * @throws NoSuchElementException if there is no line to return
    139     */
    140    public String nextLine() {
    141        if (!hasNext()) {
    142            throw new NoSuchElementException("No more lines");
    143        }
    144        final String currentLine = cachedLine;
    145        cachedLine = null;
    146        return currentLine;
    147    }
    148
    149    /**
    150     * Closes the underlying {@code Reader}.
    151     * This method is useful if you only want to process the first few
    152     * lines of a larger file. If you do not close the iterator
    153     * then the {@code Reader} remains open.
    154     * This method can safely be called multiple times.
    155     *
    156     * @throws IOException if closing the underlying {@code Reader} fails.
    157     */
    158    @Override
    159    public void close() throws IOException {
    160        finished = true;
    161        cachedLine = null;
    162        IOUtils.close(bufferedReader);
    163    }
    164
    165    /**
    166     * Unsupported.
    167     *
    168     * @throws UnsupportedOperationException always
    169     */
    170    @Override
    171    public void remove() {
    172        throw new UnsupportedOperationException("remove not supported");
    173    }
    174
    175    //-----------------------------------------------------------------------
    176    /**
    177     * Closes a {@code LineIterator} quietly.
    178     *
    179     * @param iterator The iterator to close, or {@code null}.
    180     * @deprecated As of 2.6 deprecated without replacement. Please use the try-with-resources statement or handle
    181     * suppressed exceptions manually.
    182     * @see Throwable#addSuppressed(java.lang.Throwable)
    183     */
    184    @Deprecated
    185    public static void closeQuietly(final LineIterator iterator) {
    186        IOUtils.closeQuietly(iterator);
    187    }
    188
    189}