sony
sony

Reputation: 1587

Scanning sentences from an Android Raw Resource file

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.

Upvotes: 2

Views: 1104

Answers (2)

PermGenError
PermGenError

Reputation: 46408

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.

Upvotes: 3

ianhanniballake
ianhanniballake

Reputation: 199825

Instead of using

s.next()

use

s.nextLine()

per Scanner.nextLine

Upvotes: 1

Related Questions