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*/ 
See also  Java Developer Jobs: Your Guide to Landing the Perfect Position in 2024
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist