user1254261
user1254261

Reputation: 142

reading multiple lines in file upload

can anyone tell me how to read multiple lines and store their value.

eg:file.txt

Probable Cause: The network operator has issued an alter attribute command for
the specified LCONF assign. The old value and the new value are show
Action Taken : The assign value is changed from the old value to the new
value. Receipt of this message does not guarantee that the new attribute
value was accepted by clients who use it. Additional messages may be.

Probable Cause: The network operator has issued an info attribute command for
the specified LCONF assign. The default value being used is displaye
Action Taken : None. Informational use only.

In the above file, Probable Cause and Action Taken are the column of a database table. And after Probable Cause: those are the value to be stored in the database table for probable cause column, same goes with action taken.

So how can i read the multiple lines and store their value? I have to read the value for probable cause until the line comes with Action Taken. I'm using BufferedReader and the readLine() method to read one line at a time. So can anyone tell me how to read directly from probable cause to action taken no matter how many line comes between them.

Upvotes: 0

Views: 309

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502406

The simplest way is probably to just keep a List<String> for each value, with loops something like this:

private static final String ACTION_TAKEN_PREFIX = "Action Taken ";

...

String line;
while ((line = reader.readLine()) != null)
{
    if (line.startsWith(ACTION_TAKEN_PREFIX))
    {
        actions.add(line.substring(ACTION_TAKEN_PREFIX))
        // Keep reading the rest of the actions
        break;
    }
    causes.add(line);
}
// Now handle the fact that either we've reached the end of the file, or we're
// reading the actions

Once you've got a "Probable Cause" / "Actions Taken" pair, convert the list of strings back to a single string, e.g. joining with "\n", and then insert in the database. (The Joiner class in Guava will make this easier.)

The tricky bit is dealing with anomalies:

  • What happens if you don't start with a Probable Cause?
  • What happens if one probable cause is followed by another, or one set of actions is followed by another?
  • What happens if you reach the end of the file after reading a probably cause but no list of actions?

I don't have the time to write out a complete solution now, but hopefully the above will help to get you going.

Upvotes: 1

Related Questions