如何使用FileInputStream从android中的drawable或任何其他文件夹中读取.txt文件?
我的drawable文件夹中有一个.txt文件。如何读取文件并在Textview中设置?
答案 0 :(得分:3)
试试这个,你可以从drawable文件夹中读取文件
String data = "";
StringBuffer sbuffer = new StringBuffer();
InputStream is = this.getResources().openRawResource(+
R.drawable.filetoread);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is != null) {
try {
while ((data = reader.readLine()) != null) {
sbuffer.append(data + "\n");
}
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
data = sbuffer.toString(),
}
答案 1 :(得分:1)
为什么要将.txt
保留在drawable/
文件夹中?最好将它保存在assets
文件夹中,并按照此SO中的说明进行阅读。
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
}
}
}