×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Understanding LineNumberReader
 

Submitted by: M S Sridhar(sridhar.ms@gmail.com)

Tuesday Jul 3rd 2018 by M S Sridhar

Language: Java, Expertise: Intermediate - Learn more about what you can do with LineNumberReader in Java.

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 UsingLineNumberReader
Total lines in UsingLineNumberReader.java: 35

*/ 
Home
Mobile Site | Full Site
Copyright 2018 © QuinStreet Inc. All Rights Reserved