简体   繁体   中英

InputStream reading from assets in Android

I have a wordlist saved in the assets folder in my app and i want to be able to read each word in, check it against a string and then repeat for how many words there are in the word list.

To do this though i need to be able to use a stream reader that has a readLine() method.

For reading from assets previously i have been using:

AssetManager am = getAssets();
InputStream in = am.open("wordlist.txt");
int data;
while((data=in.read())!=-1){
    System.out.println((char)data)
}in.close();

But this doesnt read in lines. I could check if each " data " is a newline char but is there a better way to do this?

If I replace InputStream I need to find an alternative that works with AssetManager Just so you know the WordList (50,000 words) is quite long so the algorithm needs to be quite quick

I beleive this does what you want...

private String readFileFromAssets(String filename)
{
StringBuilder sb = new StringBuilder();
try
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open(filename), "UTF-8"));

    // do reading, usually loop until end of file reading
    String mLine = reader.readLine();
    while(mLine != null)
    {
    // process line
    sb.append(mLine);
    mLine = reader.readLine();
    }

    reader.close();
} catch(IOException e)
{
    // log the exception
    e.printStackTrace();
}

return sb.toString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM