Get data from a specific line in a text file using BufferedReader

advertisements

I am currently building an application that is extracting values from a text file inside a project. Somehow managed extract data from specific lines but don't seem to get the right one.

Here is the code:

 private String getInputsFromATextFile(int item) throws FileNotFoundException {
    InputStream is = this.getResources().openRawResource(R.drawable.input);
    StringBuilder builder = new StringBuilder();
    int lineNo = 0;
    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while((line = reader.readLine()) != null){
            lineNo++;
            if(lineNo == item){
                builder.append(reader.readLine());
            }

        }
        reader.close();
    }
    catch (IOException e){
        e.printStackTrace();
    }
    return builder.toString();
}

And here are the text file contents:

20.45
21.65
1
225
4102
401
3
3
6
1
196.41
64.11
7
3
5
2
144.01
3
452.33
12
701.33
33
78.12
12
123.90
4
25.00
10
6.51
30.98
2.50
Spiderman
100.00
90
150.00
100
10
34
12
James
1267
Joshue
401
Christelle
3050
Ryan
888
Hanna
5
13
24
9
5
3
50

Suppose we assign a certain line number in a parameter. This method returns the exact next data from which the line number is assigned. Although, maybe I can adjust to the output that it always returns (lineNo + 1), but if in case I assigned '0' (zero) in the parameter, it instead returns null. Why is that so? I must be missing something really important.


That's because you're reading the line again in the statement builder.append(reader.readLine()). Notice that you've already read it in while loop.

So, the correct statement would be: builder.append(line);