HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / I/O / Java LineNumberReader

Java LineNumberReader

For reading a file line by line, the LineNumberReader class could be a perfect choice.

1. LineNumberReader

LineNumberReader is a subclass of the BufferedReader class and allows us to keep track of which line we are currently processing.

Line numbering begins at 0 (similar to array indices). Whenever the LineNumberReader encounters a line terminator by the wrapped Reader, the line number is incremented.

We can get the current line number by calling the getLineNumber() method.

LineNumberReader also enables us to reset the current line number to another number, by calling the setLineNumber() method.

LineNumberReader can be handy if we are parsing a text file that can contain errors. When reporting the error to the user, it is easier to correct the error if the error message includes the line number.

2. LineNumberReader Example

Let’s build a quick example to show the capabilities of LineNumberReader.

This is the file content which I will use to read using LineNumberReader in below example.

firstName=Lokesh
lastName=Gupta
blog=howtodoinjava
technology=java

Example 1: Java program to read a file line by line using LineNumberReader

In the given example, we are iterating over the lines using the method lineNumberReader.readLine() until it returns null. A null value means that all the lines in the file have been read.

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

public class LineNumberReaderExample
{
   public static void main(String[] args)
   {
      readFromFile("app.properties");
   }

   private static void readFromFile(String filename)
   {
      LineNumberReader lineNumberReader = null;
      try
      {
         //Construct the LineNumberReader object
         lineNumberReader = new LineNumberReader(new FileReader(filename));
         
         //Print initial line number 
         System.out.println("Line " + lineNumberReader.getLineNumber());
         
         //Setting initial line number
         lineNumberReader.setLineNumber(5);
         
         //Get current line number
         System.out.println("Line " + lineNumberReader.getLineNumber());
         
         //Read all lines now; Every read increase the line number by 1
         String line = null;
         while ((line = lineNumberReader.readLine()) != null)
         {
            System.out.println("Line " + lineNumberReader.getLineNumber() + ": " + line);
         }
      } 
      catch (Exception ex)
      {
         ex.printStackTrace();
      } finally
      {
         //Close the LineNumberReader
         try {
            if (lineNumberReader != null){
               lineNumberReader.close();
            }
         } catch (IOException ex){
            ex.printStackTrace();
         }
      }
   }
}

Program Output:

Line 0
Line 5
Line 6: firstName=Lokesh
Line 7: lastName=Gupta
Line 8: blog=howtodoinjava
Line 9: technology=java

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. sri

    August 28, 2014

    Thank you so much.I resolved the problem i comment out the title fields.Anyway thanks once again for your immediate response.

    • Lokesh Gupta

      August 28, 2014

      I am glad that you made it.

  2. sri

    August 27, 2014

    public static byte[] buildDynamicTabularReport(
    final ReportingTemplate template, final ReportBeans beansHolder,
    String outputFormat) throws CMPSSException {

    final String METHODNAME = “buildReport “;
    logger.debug(“Inside ” + CLASSNAME + METHODNAME);

    String reportSubTitle = beansHolder.getReportSubTitle();

    JRDataSource collection = null;

    AdhocConfiguration configuration = new AdhocConfiguration();
    byte[] reportFileByteArray = null;

    String title = template.getTemplateName();

    title = “Report Name : ” + title;

    title = title + “\n\n”;

    if (collection == null && beansHolder.getReportMap() != null) {

    JRMapCollectionDataSource mapCollection = null;
    mapCollection = ReportFactory.getReportCollectionMap(beansHolder
    .getReportMap());
    configuration = ReportFactory.getReportConfiguration(
    template.getTemplateJson(), mapCollection, reportSubTitle);

    if (mapCollection != null && mapCollection.getRecordCount() == 0) {
    reportSubTitle = “No matching records found” + “”;
    } else {

    reportSubTitle = “”;
    }

    title = “”;
    reportSubTitle = “”;

    collection = mapCollection;

    } else {

    JRBeanCollectionDataSource beanCollection = null;
    configuration = ReportFactory.getReportConfiguration(
    template.getTemplateJson(), reportSubTitle);
    beanCollection = ReportFactory.getReportCollection(beansHolder
    .getReportBeans());
    if (beanCollection != null && beanCollection.getRecordCount() == 0) {
    reportSubTitle = “No matching records found” + “”
    + reportSubTitle;
    }

    collection = beanCollection;

    }

    reportFileByteArray = publishReport(collection, configuration, title,
    reportSubTitle, outputFormat);

    return reportFileByteArray;

    }

    private static byte[] publishReport(final JRDataSource beanSource,
    final AdhocConfiguration configuration, String title,
    String subTitle, String outputFormat) throws CMPSSException {

    final String METHODNAME = “publishReport “;
    logger.debug(“Inside ” + CLASSNAME + METHODNAME);

    try {

    ReportCustomizer customizer = new ReportCustomizer();
    JasperReportBuilder reportBuilder = AdhocManager.createReport(
    configuration.getReport(), customizer);

    reportBuilder.setDataSource(beanSource);

    // Get Today’s Date
    String date = getCurrentDate();
    date = “”;
    if (beanSource instanceof JRMapCollectionDataSource) {

    reportBuilder.title(cmp.verticalList(cmp.horizontalList(cmp
    .text(title).setStyle(titleStyle), cmp.text(date)
    .setStyle(normalRightStyle)), cmp.text(subTitle)
    .setStyle(subTitleStyle)));
    } else {
    reportBuilder
    .title(cmp.verticalList(
    cmp.image(
    ReportFactory.class
    .getResource(“/resources/Report_Logo.jpg”))
    .setImageScale(
    ImageScale.FILL_PROPORTIONALLY),
    cmp.horizontalList(
    cmp.text(title).setStyle(titleStyle),
    cmp.text(date).setStyle(
    normalRightStyle)),
    cmp.text(subTitle).setStyle(subTitleStyle)));
    }

    StyleBuilder columnTitleStyle = stl.style(boldCenteredStyle)
    .setBorder(stl.pen1Point())
    .setBackgroundColor(new Color(0xFFB749));
    StyleBuilder columnDetailStyle = stl.style(normalCenterStyle)
    .setBorder(stl.pen1Point());
    reportBuilder.setColumnStyle(columnDetailStyle);
    reportBuilder.setColumnTitleStyle(columnTitleStyle);

    // For Blank Report Show Outline
    reportBuilder
    .setWhenNoDataType(WhenNoDataType.ALL_SECTIONS_NO_DETAIL);
    // Save Report in Byte Array and return
    ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
    java.io.OutputStream out = bytestream;

    if (outputFormat == null
    || outputFormat.equals(Constants.TEMPLATE_OUTPUT_TYPE_PDF)) {
    reportBuilder.setSummaryWithPageHeaderAndFooter(true);
    reportBuilder.pageHeader(cmp.pageNumber()
    .setHorizontalAlignment(HorizontalAlignment.RIGHT));
    reportBuilder.toPdf(out);
    } else if (outputFormat
    .equals(Constants.TEMPLATE_OUTPUT_TYPE_EXCEL)) {
    reportBuilder.setIgnorePagination(true);
    JasperXlsxExporterBuilder xlsxExporterBuilder = export
    .xlsxExporter(out).setRemoveEmptySpaceBetweenRows(true)
    .setRemoveEmptySpaceBetweenColumns(true)
    .setIgnorePageMargins(true);

    //.setOnePagePerSheet(true);

    // reportBuilder.toXlsx(out);
    reportBuilder.toXlsx(xlsxExporterBuilder);
    }

    byte[] reportFileByteArray = IOUtils
    .toByteArray(new ByteArrayInputStream(bytestream
    .toByteArray()));
    return reportFileByteArray;

    } catch (DRException e) {
    e.printStackTrace();
    logger.error(
    CLASSNAME + METHODNAME + “Error while building Report”, e);
    throw new CMPSSException(CMPSSMessage.getMessage(e.getMessage()));
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    logger.error(
    CLASSNAME + METHODNAME + “Error while building Report”, e);
    throw new CMPSSException(CMPSSMessage.getMessage(e.getMessage()));
    } catch (IOException e) {
    logger.error(
    CLASSNAME + METHODNAME + “Error while building Report”, e);
    throw new CMPSSException(CMPSSMessage.getMessage(e.getMessage()));
    } catch (Exception e) {
    e.printStackTrace();
    logger.error(
    CLASSNAME + METHODNAME + “Error while building Report”, e);
    throw new CMPSSException(CMPSSMessage.getMessage(e.getMessage()));
    }
    }

    In the above code there is one method name of “publish report” method we are getting the EXCEL (for this line JasperXlsxExporterBuilder) and there we are adding one property “setRemoveEmptySpaceBetweenColumns” it is removing the spaces but same property for row also it is not removing.Can you please tell me the solution ?

    • Lokesh Gupta

      August 27, 2014

      Hi Sri, code you have written is correct. I am really unable to find the bug by inspecting the code. I will find time to setup the jasper in my machine, and try to write an example for you.

  3. sri k

    August 27, 2014

    Hi Guptha

    I created Jasper reports it is generated by Excel sheet.But the problem is in my excel i am getting the space between the rows.The row starting from the 3rd number.Column is displaying properly but row is not coming properly.Can you please tell me how to delete that empty rows using jasper reports

    Thanks
    Sri.K

    • Lokesh Gupta

      August 27, 2014

      Hi Sri, How can help you without knowing what code you have written so far? Please share some code which is creating problem.

  4. Teja

    August 21, 2014

    1. Can i use line number to read a file backwards???
    2. With line number , will i be able to skip / read the desired line i want ?? (like i want to read only 35-45 lines)

    • Lokesh Gupta

      August 21, 2014

      I suspect that there is a way to this. Java IO APIs read in sequential manner. Only API for random access I am aware of is RandomAccessFile, that also does not provide the functionality you are seeking.

  5. varun

    August 11, 2014

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

    public class LineNumberReaderExample
    {
    public static void main(String[] args)
    {

    try{

    File file =new File(“c:\\data.txt”);

    if(file.exists()){

    FileReader fr = new FileReader(file);
    LineNumberReader lnr = new LineNumberReader(fr);

    int linenumber = 0;

    while (lnr.readLine() != null){
    linenumber++;
    }

    System.out.println(“Total number of lines : ” + linenumber);

    lnr.close();

    }else{
    System.out.println(“File does not exists!”);
    }

    }catch(IOException e){
    e.printStackTrace();
    }

    }
    }

    • Lokesh Gupta

      August 11, 2014

      Thanks for sharing it.

  6. varun

    August 11, 2014

    Java program to print the content to a file with line numbers

Comments are closed on this article!

Search Tutorials

Java IO

  • Java IO Introduction
  • Java How IO works?
  • Java IO vs NIO
  • Java Create File
  • Java Write to File
  • Java Append to File
  • Java Read File
  • Java Read File to String
  • Java Read File to Byte[]
  • Java Make File Read Only
  • Java Copy File
  • Java Copy Directory
  • Java Delete Directory
  • Java Current Working Directory
  • Java Read/Write Properties File
  • Java Read File from Resources
  • Java Read File from Classpath
  • Java Read/Write UTF-8 Data
  • Java Check if File Exist
  • Java Create Temporary File
  • Java Write to Temporary File
  • Java Delete Temporary File
  • Java Read from Console
  • Java Typesafe input using Scanner
  • Java Password Protected Zip
  • Java Unzip with Subdirectories
  • Java Generate SHA/MD5
  • Java Read CSV File
  • Java InputStream to String
  • Java String to InputStream
  • Java OutputStream to InputStream
  • Java InputStreamReader
  • Java BufferedReader
  • Java FileReader
  • Java LineNumberReader
  • Java StringReader
  • Java FileWriter
  • Java BufferedWriter
  • Java FilenameFilter
  • Java FileFilter

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces