简体   繁体   中英

How do I make this bufferedReader loop keep going?

I have a BufferedReader loop that checks if the next lines != null, If the line has text on it, the reader will read the line, now I successfully made it do this, it reads the line and then It wont read the next because it already went thought the if loop, what would i do to make it keep reading lines until there are no more lines to read? I could use a while loop but Im kinda confused as to where to put it.

int numberOfLines = 0;
String[] textData = new String[numberOfLines];

if (red.readLine() != null) {
    numberOfLines++;
    int i;
    for (i = 0; i < numberOfLines; i++) {
        textData[i] = red.readLine();
        //System.out.println(textData[i]);
        textArea.append("\n");  //Break line after every read line
        textArea.append(textData[i]);
    }
}

You have:

   int numberOfLines = 0;
   String[] textData = new String[numberOfLines];

So your array has zero size. Doing this later:

numberOfLines++;

does not grow the array. In fact, you can't grow an array. You want a data structure (like an ArrayList) that can grow.

See also How to read from files with Files.lines(...).forEach(...)? for an alternative way.

Use a while loop. And because Java arrays are fixed length, you'll need to copy the elements into your newly expanded array. Also, please use System.lineSeparator() (not every system uses \\n ). Something like,

String[] textData = new String[0];
String line;
int i = 0;
while ((line = red.readLine()) != null) {
    String[] dest = new String[textData.length + 1];
    System.arraycopy(textData, 0, dest, 0, textData.length);
    dest[i++] = line;
    textData = dest;
    textArea.append(System.lineSeparator() + line);
}

Alternatively, you could read into a Collection (like ArrayList ). Something like,

List<String> textData = new ArrayList<>();
String line;
while ((line = red.readLine()) != null) {
    textData.add(line);
    textArea.append(System.lineSeparator() + line);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM