Issue
I added a sample text file in Android res/raw folder and I am trying to add each line of the file into a String array list.
For e.g., say the sample text file contains the following lines
Sample Line One
Sample Line Two
Sample Line Three
I would like to add these three sentences as three Strings into a String Array List. I tried the following piece of code:
List<String> sampleList = new ArrayList<String>();
Scanner s = null;
s = new Scanner(getResources().openRawResource(R.raw.sample));
while (s.hasNextLine()){
sampleList.add(s.next());
}
s.close();
The above code adds each word in the array list and results in an array size of 9 rather than adding each sentence with an expected array size of 3. Thanks for your help.
Solution
use Scanner#nextLine() instead of Scanner#next()
sampleList.add(s.nextLine());
Scanner use's white space as a default delimiter. Scanner#next()
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
You can also set the delimiter of the scanner to next line(\n) using Scanner#useDelimiter(delim).
s = new Scanner(getResources().openRawResource(R.raw.sample)).useDelimiter("\n");
while (s.hasNextLine()){
sampleList.add(s.next());
}
and now you can use Scanner.next()
as it uses next line(\n) as the delimiter.
Answered By - PermGenError
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.