以下是我在缓冲阅读活动做扩展/修改,以满足您的需求
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