Android中如何读取txt文件的内容以及其编码问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//读取文本文件中的内容
public static String ReadTxtFile(String strFilePath)
{
String path = strFilePath;
String content = ""; //文件内容字符串
//打开文件
File file = new File(path);
//如果path是传递过来的参数,可以做一个非目录的判断
if (file.isDirectory())
{
Log.d("TestFile", "The File doesn't not exist.");
}
else
{
try {
InputStream instream = new FileInputStream(file);
InputStreamReader inputStreamReader = null;
try {
inputStreamReader = new InputStreamReader(instream, "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();
}
content = sb.toString();
}
catch (java.io.FileNotFoundException e)
{
Log.d("TestFile", "The File doesn't not exist.");
}
catch (IOException e)
{
Log.d("TestFile", e.getMessage());
}
}
return content;
}