Java IO Tutorial - Java LineNumberReader.readLine()








Syntax

LineNumberReader.readLine() has the following syntax.

public String readLine()  throws IOException

Example

In the following code shows how to use LineNumberReader.readLine() method.

/*from  w w w .  j a  va  2  s  .  c o  m*/

import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

public class Main {
  public static void main(String[] args) throws IOException {

    String str;
    // create new reader
    FileReader fr = new FileReader("C:/test.txt");
    LineNumberReader lnr = new LineNumberReader(fr);

    // read lines till the end of the stream
    while ((str = lnr.readLine()) != null) {
      int i = lnr.getLineNumber();
      System.out.print("(" + i + ")");

      // prints string
      System.out.println(str);
    }
    lnr.close();
  }
}