Reputation: 4225
I have Stream of String data which could have value
system_id "2.2.2.1"
component_id 6
sequence_number 11
timestamp 1459202982
kv {
key "val1"
}
kv {
key "val2"
}
kv {
key "val3"
}
system_id "2.2.2.1"
component_id 6
sequence_number 15
timestamp 1459202982
kv {
key "val4"
}
kv {
key "val5"
} and so on....
All i am interested is value of key, which are val1, val2, val3....
I am using scanner as shown below,
scan = new Scanner(new File("kvfiles/file1")).useDelimiter("\\s+kv\\s+\\{\\s+"); //To ignore any thing before "kv"
while (scan.hasNext()) {
String str = scan.next();
finalString = str.split("\\s+\\}")[0];
}
This code is working fine when file is started with "kv {" but in above case when file is started with below mention value, parser is giving error.
system_id "2.2.2.1"
component_id 6
sequence_number 11
timestamp 1459202982
Any idea how can i skip this block of data?
Note: This block of data could come occasionally after some "kv { }" tags, all i need is to ignore it whenever it comes.
Upvotes: 0
Views: 115
Reputation: 26
Why dont you take just the interesting line?
public class Test {
public static void main(String[] args) throws FileNotFoundException {
Pattern p = Pattern.compile("\\s+key.+");
Scanner sc = new Scanner(new File("src/main/resources/test.txt"));
while (sc.hasNextLine()) {
sc.nextLine();
String theLineYouWant = sc.findInLine(p);
// scnn this line again here
if (theLineYouWant != null) {
System.out.println(theLineYouWant);
}
}
}
}
Please keep in mind that the file mentioned above is just my own test file.
Upvotes: 1