Guide to Java LineNumberReader

For reading a file line by line, the LineNumberReader class could be a perfect choice. It is a buffered character-input stream that keeps track of line numbers.

By default, line numbering begins at 0. A line is considered to be terminated by any one of a line feed (‘\n’), a carriage return (‘\r’), combination of both (‘\r\n’)  or any of the previous terminators followed by the end of stream, or end of stream not preceded by another terminator.

1. How Does LineNumberReader Works?

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. At the end of the stream, the line number is incremented last time.

The LineNumberReader provides the following important methods:

  • getLineNumber() : gets the current line number where the reader is reading.
  • setLineNumber(int lineNumber) : sets the current line number. Note that this method does not change the current position of reader in the stream; it only changes the value that will be returned by getLineNumber().
  • readLine() : reads the current line, not including any line termination characters, or null if the end of the stream has been reached.
  • reset() : resets the stream to the most recent mark created by the mark() method.
  • mark(n) : marks the present position in the stream. Calling reset() will attempt to reposition the stream to this point, and will also reset the line number appropriately.

LineNumberReader can be useful 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. Using LineNumberReader

Let’s build a quick example to show the capabilities of LineNumberReader. This is the file content that I will use to read using LineNumberReader in the below example.

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

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.

final String fileName = "app.properties";

try(LineNumberReader 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();
} 

Program Output:

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

Happy Learning !!

Source Code on Github

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

11 thoughts on “Guide to 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 related technologies, the best practices, algorithms, and interview questions.