直接代码:
onCreate(){
tv_id= (TextView) findViewById(R.id.tv_id);
InputStream inputStream = getResources().openRawResource(R.raw.myfile);//myfile是txt文件名
String string = TxtReader.getString(inputStream);
tv_id.setText(string);
}
public static class TxtReader {
public static String getString(InputStream inputStream) {
InputStreamReader inputStreamReader = null;
try {
inputStreamReader = new InputStreamReader(inputStream, "utf-8");//注意修改格式
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuffer sb = new StringBuffer("");
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
/**
* 通过txt文件的路径获取其内容
*
* @param filepath
* @return
*/
public static String getString(String filepath) {
File file = new File(filepath);
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return getString(fileInputStream);
}
}