Reputation: 1725
I want to know how can I do to extract a substring from a text file in android:
the text file is as shown below :
[start_delimeter]
0|1|text1
0|1|text2
0|1|text3
0|1|text4
[end_delimiter]
I want to extract strings between start_delimeter and end_delimiter.
How can I do that in java language/ android ??
Upvotes: 1
Views: 4540
Reputation: 43504
filename.txt
)BufferedReader
) till you read the start delimiterPattern
and Matcher
till the end delimiter is found (or with String.split("|")
) // first get the file from the assets
InputStream is = context.getAssets().open("filename.txt");
try {
// start reading (line by line)
BufferedReader r = new BufferedReader(new InputStreamReader(is));
// wait for the start delimiter
String line;
while ((line = r.readLine()) != null)
if (line.equals("[start_delimiter]"))
break;
// this is the pattern for the data "int|int|String":
Pattern p = Pattern.compile("\\|(\\d+)\\|(\\d+)\\|(.+)");
// read it line by line...
while ((line = r.readLine()) != null) {
// ... till the end comes (end delimiter)
if (line.equals("[end_delimiter]"))
break; //done
// if the data matches the pattern...
Matcher m = p.matcher(line);
if (m.matches()) {
// ... handle it!
int first = Integer.parseInt(m.group(1));
int second = Integer.parseInt(m.group(2));
String text = m.group(3);
//...
}
}
} finally {
is.close();
}
Upvotes: 3
Reputation: 240900
I want to extract strings between start_delimeter and end_delimiter.
How can I do that in java language/ android ??
Read file line by line into String. then
str.subString(startIndex,endIndex);
Upvotes: 1
Reputation: 45568
Use a BufferedReader
and read the file line by line.
BufferedReader r = ...;
//drop until we hit the delimiter
while (!r.readLine().equals("[start_delimeter]"));
String line;
while (!(line=r.readLine()).equals("[end_delimiter]")) {
//do something with "line" here
}
Upvotes: 0
Reputation: 4593
Simply put, I would read the file line-by-line with a BufferedReader. Once the starting delimiter is found evaluate each subsequent line to see if it's the ending delimiter. If it isn't the delimiter, write the string to a collection. Once the ending delimiter is reached, stop reading and close the reader.
Upvotes: 0