Ayyappa Pusarla Ayyappa Pusarla - 4 months ago 8
Java Question

want to print a data according to row in text file

I have a text file of data like this

username=Ayyappa,password=123
username=venkata,password=456
username=Bhargav,password=789
username=Rama,password=158
username=Pusarla,password=968


i want to print the data at row number 2
(My expected output is username=venkata,password=456)

Funtion written:

public class TestDataReader {
public static String getrowvalue(String FileName, int rownum) throws IOException{

FileReader fr = new FileReader(FileName);
BufferedReader br = new BufferedReader(fr);
String lineString = null;
while((lineString = br.readLine())!= null){
int counter = 1;
if(counter == rownum){
System.out.println(lineString);
counter ++;
}
}

return lineString;
}

}


i called this function in another class

TestDataReader.getrowvalue("F:\WS_Finsys_Ayyappa\Ejagruti\TestData\login.txt", 2);

but when i am calling this function it is printing all the row data but not with row data i passed in this case i passed rownum 2 to get the row data

Answer

Your mistake is here: you simply flush counter value each time in loop:

int counter = 1;

So change it to:

 int counter = 1;
 while((lineString = br.readLine())!= null){
        if(counter == rownum){
            System.out.println(lineString);
        }
        counter++;
    }

UPD: Also, as @Lemm Ras mentioned, you have to move counter incrementation outside if statement.

Comments