以下是我在緩衝閱讀活動做擴展/修改,以滿足您的需求
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
編輯:我的答案也許是無用的,如果你的問題是如何做到這一點的活動之外。如果你的問題只是如何從資產中讀取文件,那麼答案就在上面。
UPDATE:
要打開一個文件中指定類型只需在InputStreamReader的通話如下補充類型。
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt"), "UTF-8"));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
編輯
由於@Stan在註釋中說,我給的代碼沒有總結線。每過一遍就更換一次mLine
。這就是爲什麼我寫了//process line
。我假定該文件包含某種數據(即聯繫人列表),並且每行應該分開處理。
如果您只是想要在沒有任何處理的情況下加載文件,則必須在每次使用StringBuilder()
時總結mLine
並追加每遍。
ANOTHER編輯
根據@Vincent的評論我增加了finally
塊。
另請注意,在Java 7和更高版本中,您可以使用try-with-resources
來使用最近的Java的AutoCloseable
和Closeable
功能。
背景
在@LunarWatcher指出getAssets()
是context
一個class
評論。因此,如果您將其稱爲activity
之外,則需要引用它並將該上下文實例傳遞給該活動。
ContextInstance.getAssets();
這在@Maneesh的答案中有解釋。所以如果你對他的回答有幫助,因爲那是他指出的。
此代碼失敗,因爲它會取代mline的內容,每過一遍 – Stan 2014-01-16 18:38:19
@Stan,然後在評論中寫下它,讓作者決定是否要更新它。編輯是爲了提高清晰度,而不是改變意義。代碼修訂應始終首先發布爲註釋。 – KyleMit 2014-01-16 18:39:59
好吧,我明白了,thanx!它很好,你在EDIT中提到了功能。我會盡快刪除這個我的評論,因爲沒有建設性等。我也投了你的評論以上 – Stan 2014-01-17 10:36:57