dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


advertisement
 

Tip: Understanding LineNumberReader

Learn more about what you can do with LineNumberReader in Java.


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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

*/ 

 

Visit the DevX Tip Bank

 





   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date