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?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

11 thoughts on “Java LineNumberReader”

  1. 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 ?

    Reply
    • 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.

      Reply
  2. 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

    Reply
  3. 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)

    Reply
  4. 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();
    }

    }
    }

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.