[英]InputStream reading from assets in Android
我在應用程序的Assets文件夾中保存了一個單詞列表,我希望能夠讀取每個單詞,根據字符串檢查它,然后重復單詞列表中有多少個單詞。
為此,盡管我需要能夠使用具有readLine()
方法的流閱讀器。
為了讀取以前的資產,我一直在使用:
AssetManager am = getAssets();
InputStream in = am.open("wordlist.txt");
int data;
while((data=in.read())!=-1){
System.out.println((char)data)
}in.close();
但是,這不是一行。 我可以檢查是否每個“ data
”是換行char
,但有沒有更好的方式來做到這一點?
如果我替換InputStream
我需要找到一個可與AssetManager
一起使用的替代方法就像您知道WordList(50,000個單詞)很長,因此算法需要非常快
我相信這是您想要的...
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.