Android从assets和raw中读取txt文件

时间:2021-10-01 17:46:39

方法一、将要读取的txt文件拷贝到Android工程目录下的assets文件夹下

方法二、在res文件夹下新建raw文件夹,将txt拷贝到该目录下


本方法是从assets中读取

/**
* 从assets中读取txt
*/
private void readFromAssets() {
try {
InputStream is = getAssets().open("qq.txt");
String text = readTextFromSDcard(is);
textView.setText(text);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


本方法是从raw中读取

/**
* 从raw中读取txt
*/
private void readFromRaw() {
try {
InputStream is = getResources().openRawResource(R.raw.qq);
String text = readTextFromSDcard(is);
textView.setText(text);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

本方法是解析输入流,返回txt中的字符串

/**
* 按行读取txt
*
* @param is
* @return
* @throws Exception
*/
private String readTextFromSDcard(InputStream is) throws Exception {
InputStreamReader reader = new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuffer buffer = new StringBuffer("");
String str;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
buffer.append("\n");
}
return buffer.toString();
}