这是我在一项活动中所做的活动,用于缓冲读取扩展/修改以符合您的需求
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
}
}
}
编辑:如果您的问题是在活动之外如何做,我的答案也许没用。如果您的问题仅是如何从资产读取文件,则答案在上方。
更新:
要打开指定类型的文件,只需在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。我假设文件包含某种数据(即联系人列表),并且每一行都应分别处理。
万一您只想加载文件而不进行任何类型的处理,则必须mLine在每次通过时总结StringBuilder()并附加每个通过。
另一个编辑
根据@Vincent的评论,我添加了该finally块。
另请注意,在Java 7及更高版本中,您可以使用try-with-resources来使用最新Java 的AutoCloseable和Closeable功能。
语境
@LunarWatcher在评论中指出这getAssets()是classin中的context。因此,如果您在外部调用它,则activity需要引用它并将上下文实例传递给活动。
ContextInstance.getAssets();
@Maneesh的答案对此进行了解释。因此,如果这对您有用,请支持他的答案,因为那是他指出的。