Stanley Mungai
Stanley Mungai

Reputation: 4150

Print out a line from a file if it contains certain String

I have a file which I want to Print out the Lines containing the String A/C NO:

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import org.apache.commons.io.FileUtils;
public class TestFndString {
    public static void main(String[] args) throws IOException {
        String str1 = FileUtils.readFileToString(new File("C:/Testing.txt"));
        LineNumberReader lnr = new LineNumberReader(new FileReader(new File("C:/Testing.txt")));
        lnr.skip(Long.MAX_VALUE);
        if (str1.contains("A/C NO:")) {
            int num = lnr.getLineNumber();
            System.out.println(num);
        }

    }
}

My Code is Printing 2 as the line Number which contains that String while the String is actually in line 3. Here is My File sample:

jhsdjshdsjhdjs
sdkjsdkjskdjskjd
AjhsdjhsdjhA/C NO: jhsdjhsdjssdlk

Obviously I do not trust this to read a larger file or a group of files. What is the best way to do this?

Upvotes: 0

Views: 2714

Answers (3)

Trying
Trying

Reputation: 14278

LineNumberReader starts from 0 so increment 1 for expected result.

from DOCS:

By default, line numbering begins at 0. This number increments at every line terminator as the data is read, and can be changed with a call to setLineNumber(int). Note however, that setLineNumber(int) does not actually change the current position in the stream; it only changes the value that will be returned by getLineNumber().

so two ways you can get expected result:

1. 

LineNumberReader lnr = new 
                  LineNumberReader(new FileReader(new File("C:/Testing.txt")));        
    if (str1.contains("A/C NO:")) {
        int num = lnr.getLineNumber();
        System.out.println(num+1);
    }




2.  OR you can use setLineNumber(int) as mentioned in java docs.

Upvotes: 1

An SO User
An SO User

Reputation: 24998

Line numbering, like array indexing, begins with 0. Incrementing it with one will give you the right answer.

if (str1.contains("A/C NO:")) {
     int num = lnr.getLineNumber();
     System.out.println( ++num ); // see the increment using ++ ?
}  

The pre-increment operator will increment the num variable by 1 before printing it and hence you will get the desired result.

Upvotes: 2

Axel
Axel

Reputation: 14149

Line numbering begins with 0. Just add 1 to the result you get (Just look at the JavaDoc). Alternatively callsetLineNumber(1) after creating your LineNumberReader:

LineNumberReader lnr = new LineNumberReader(new FileReader(new File("C:/Testing.txt")));
lnr.setLineNumber(1);

Upvotes: 1

Related Questions