Separate line contents in the Bufferedreader loop

Asked

Viewed 275 times

3

I have files txt with approximately 5,000 items, and these do not have a pattern, for example:

10 20
30
40

50 60 70

80
90 100

I need to import this into the SQLite, where each value is 1 record. Example:

ID | VALOR
 1 |   10
 2 |   20
 3 |   30
 4 |   40
 5 |   50
 6 |   60
 7 |   70
 8 |   80
 9 |   90
10 |  100

I read the txt as follows:

try {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            text.append(line);
            text.append("\n");
        }
        bufferedReader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

In place of text.append(line); and text.append("\n");, would be like while reading each line, already "treat/separate" the values that are on the same line, so I can already bring separate ?

If I have 1 value in the row, I can already insert direct into the bank, for example:

insere(line);

But with several values on the same line ? For example:

The line with value 50 60 70, I would already break the 3 values, and run in a method to include in the bank?

If I wear a line = line.replace(" ", "\n"); before the append, he will bring me line in soft, and I can deal with if to insert or not. That would be the best solution ?

The idea is to do this right in reading, so you don’t have to create a huge variable, treat the content, and then do the insert.

1 answer

2


Do the split of line and treat each element of the array.

Anything like that:

while ((line = bufferedReader.readLine()) != null) {
    String[] values = line.split(" ");
    for(String value: values) {
        insere(value);
    }
}

See a simulation on Ideone.

  • 1

    I just added if (value.length() > 0) insere(value); inside the is, because the empty lines gave crash.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.