java – Separate line content in BufferedReader loop

Question:

I have txt files with approximately 5 thousand items, and these don't have a pattern, for example:

10 20
30
40

50 60 70

80
90 100

I need to import this to SQLite , 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 it be like while I read each line, already "treat/separate" the values ​​that are on the same line, so that I can bring them separated?

If I have 1 value on the line, I can already enter it directly in the bank, for example:

insere(line);

But what about with multiple 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 database?

If I use a line = line.replace(" ", "\n"); before append , it will bring me a blank line, and I can deal with if to insert or not. Would this be the best solution?

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

Answer:

Split the line and treat each element of the array.

Anything like this:

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

See a simulation on Ideone.

Scroll to Top