Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using BufferedReader to read a single line in Java

I have code successfully reading from a CSV. However when I try to use fileReader to read a solo line, it makes my code stop working.

Here is my code:

try {
    String line = "";
    fileReader = new BufferedReader(new FileReader(filename));

    while ((line = fileReader.readLine()) != null) {
        String[] tokens = line.split(DELIMITER);
        for (String token : tokens) {
            totalData.add(token);
            if (!artists.contains(token)) {
                artists.add(token);
            }
        }
        for (int l = 0; l <= 999; l++) {
            lineData = fileReader.readLine();
            lineArray[l] = lineData;
        }

    }
} finally {
    fileReader.close();
}

When I try to read arrayList sizes and print data I get from the arrayLists above this code below makes it stop working:

for (int l = 0; l <= 80; l++) {
    lineData = fileReader.readLine();
    lineArray[l] = lineData;
}

If I comment this for loop, everything is fine. I really need this for loop, how can I edit my code to resolve this issue? Also, what is happening?

like image 834
Justin Avatar asked Feb 20 '26 22:02

Justin


1 Answers

for (int l = 0; l <= 80; l++) {
    lineData = fileReader.readLine();
    lineArray[l] = lineData;
}

This hard code can replace a single line of code:

lineArray[i++] = line;

I corrected your code and that's what happened:

String line = "";
int i = 0;
try (BufferedReader fileReader = new BufferedReader(new FileReader(""))) {
    while ((line = fileReader.readLine()) != null) {
        lineArray[i++] = line;
        String[] tokens = line.split(DELIMITER);
        for (String token : tokens) {
            totalData.add(token);
            if (!artists.contains(token)) {
                artists.add(token);
            }
        }
    }
}
like image 158
Andrew Tobilko Avatar answered Feb 23 '26 10:02

Andrew Tobilko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!