[英]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. 我在应用程序的Assets文件夹中保存了一个单词列表,我希望能够读取每个单词,根据字符串检查它,然后重复单词列表中有多少个单词。
To do this though i need to be able to use a stream reader that has a readLine()
method. 为此,尽管我需要能够使用具有
readLine()
方法的流阅读器。
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? 我可以检查是否每个“
data
”是换行char
,但有没有更好的方式来做到这一点?
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 如果我替换
InputStream
我需要找到一个可与AssetManager
一起使用的替代方法就像您知道WordList(50,000个单词)很长,因此算法需要非常快
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.