android 读取assets下和raw下的txt文件

时间:2021-04-23 17:45:40

读取assets下txt文件夹下txt文件
TextView tv1 = (TextView) findViewById(R.id.tvShow1);
tv1.setText(getFromAssets(“txt/health.txt”));
public String getFromAssets(String fileName) {
String result = “”;
try {
InputStream in = getResources().getAssets().open(fileName);
// 获取文件的字节数
int lenght = in.available();
// 创建byte数组
byte[] buffer = new byte[lenght];
// 将文件中的数据读到byte数组中
in.read(buffer);
result = EncodingUtils.getString(buffer, ENCODING);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
//读取raw下txt文件
public String getFromRaw(int fileId){
String result = “”;
try {
InputStreamReader inputReader = new InputStreamReader( getResources().openRawResource(fileId));
BufferedReader bufReader = new BufferedReader(inputReader);
String line=”“;
result=”“;
while((line = bufReader.readLine()) != null)
result += line;
return result;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}