String content = ""; //文件内容字符串
//----FilePath 为文件全路径-------------
public String ReadTxtFileToString(String FilePath )
{
//获取文件编码
String codeformat = getCodeFormat( FilePath ).trim();
if ( codeformat.equals("") ) {
1. 读取文本文件的方法
2. //-------把文本文件读入 String, 字符串之间的分隔符为 '\n\------
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
FileInputStream fis = new FileInputStream( file );
BufferedReader reader = new BufferedReader(new
File file = new File( FilePath );
}
//打开文件
try {
codeformat = "GBK";
InputStreamReader(fis, codeformat));
String line;
//分行读取
while ( ( line = reader.readLine()) != null ) {
content += line + "\n";
}
fis.close();
reader.close();
} catch ( java.io.FileNotFoundException e ) {
Log.i( tag, FilePath + " 不存在。");
} catch (IOException e) {
Log.i( tag, "FileOperate 271 error= " + e.getMessage() );
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
}
return content;
}
2.判断文本文件的编码格式--------------
public String getCodeFormat(String filepath) {
String codeformat = "";
File file = new File(filepath);
BufferedReader reader;
String text = "";
byte[] first3bytes = new byte[3];
FileInputStream fis = null;
BufferedInputStream in = null;
try{
fis = new FileInputStream(file);
in = new BufferedInputStream(fis);
in.mark(4);
in.read(first3bytes);
in.reset();
}catch(IOException ex){
try{
in.close();
fis.close();
}catch(Exception ey){}
}
try{
in.close();
fis.close();
}catch(Exception ey){}
"utf-8"));
0xFE) {
0xFF) {
0xFF) {
if(first3bytes[0] == (byte) 0xEF && first3bytes[1] == (byte) 0xBB
&&first3bytes[2] == (byte) 0xBF) {// utf-8
codeformat = "utf-8";
//reader = new BufferedReader(newInputStreamReader(in,
}else if (first3bytes[0] == (byte) 0xFF && first3bytes[1] == (byte)
codeformat = "unicode";
//reader = new BufferedReader(new
InputStreamReader(in,"unicode"));
}else if (first3bytes[0] == (byte) 0xFE &&first3bytes[1] == (byte)
codeformat = "utf-16be";
//reader = new
BufferedReader(newInputStreamReader(in,"utf-16be"));
}else if (first3bytes[0] == (byte) 0xFF &&first3bytes[1] == (byte)
codeformat = "utf-161e";
//reader = new
BufferedReader(newInputStreamReader(in,"utf-16le"));
//reader = new BufferedReader(newInputStreamReader(in, "GBK"));
}else {
codeformat = "GBK";
}
return codeformat;
}
3. 读取文本文件并把内容保存到字符串数组
String flph = “/mnt/sdcard/files/test.txt”;
String[] sar = ReadTxtFileToString( flph).split(“\\n”);