devxlogo

Understanding LineNumberReader

Understanding LineNumberReader

LineNumberReader is a cool class in Java from which numerous line related tasks can be performed:

import java.io.FileReader;import java.io.LineNumberReader;import java.io.IOException;public class UsingLineNumberReader {   public static void main(String args[])   {      UsingLineNumberReader usingLineNumberReader = new UsingLineNumberReader();      usingLineNumberReader.proceed();   }   private void proceed()    {      LineNumberReader lineNumberReader = null;      int totalLines = 0, readChar = 0;      try       {         //Reading the source file itself to find out the total lines in this file         lineNumberReader = new LineNumberReader(new FileReader("UsingLineNumberReader.java"));         while(((readChar = lineNumberReader.read()) != -1)) {            totalLines = lineNumberReader.getLineNumber();         }      } catch(Exception e) {         System.out.println(e.getMessage());      } finally {         try         {            if(lineNumberReader!=null)               lineNumberReader.close();         } catch(Exception ee) {            System.out.println(ee.getMessage());         }      }      System.out.println("Total lines in UsingLineNumberReader.java: " + (totalLines+1));   }}/*

Expected output:

[root@mypc]# java UsingLineNumberReaderTotal lines in UsingLineNumberReader.java: 35*/ 

devx-admin

Share the Post: