For reading text file line by line apache.commons.io provides a class LineIterator
. This utility class provides better implementation with all checks to read text line by line. It uses BufferedReader
internally.
To use this file download apache.commons.io and reference it to your project or use following Gradle or Maven entry.
Gradle entry
\'org.apache.commons:commons-io:1.3.2\'
Maven Entry
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency>
Example of LineIterator to read text file line by line
FileUtils
class of commons-io provide factory method to make instance and use this class as given below.
import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; public class FileIteratorExample { public static void main(String[] args) throws IOException { File file = new File("/textfile.txt"); LineIterator it = FileUtils.lineIterator(file, "UTF-8"); try { while (it.hasNext()) { String line = it.nextLine(); // do something with line } } finally { it.close(); } } }
Apart from this it provides isValidLine overridable method to validate each line that is returned. By default this method return true. But if some one want to check validity of lines e.g. read only lines starting or ending with some text or character or contains some text then this can achieved by simply extending this class and overriding isValidLine method.
Reading line ending with some text example
import org.apache.commons.io.Charsets; import org.apache.commons.io.LineIterator; public class FileIteratorExample { public static void main(String[] args) throws IOException { File file = new File("D:/test/textfile.txt"); //Read line ending with ? MyLineIterator it = new MyLineIterator(new InputStreamReader( new FileInputStream(file), Charsets.toCharset("UTF-8")), "?"); try { while (it.hasNext()) { String line = it.nextLine(); System.out.println(line); } } finally { it.close(); } } } class MyLineIterator extends LineIterator { private String lineEndsWith; public MyLineIterator(Reader reader, String lineEndsWith) throws IllegalArgumentException { super(reader); if (lineEndsWith == null) { throw new IllegalArgumentException("lineEndsWith"); } this.lineEndsWith = lineEndsWith; } @Override protected boolean isValidLine(String line) { return line.endsWith(lineEndsWith); } }
You can implement your check here for reading lines conditionally.