单单读取TXT文件的话,用BufferedReader效率比较高,也方便一些。需要注意的是,TXT文件在不同版本的*作系统中编*格式会有所不同,笔者曾经试过在两台同样的WIN7系统下,一个格式为"UTF-8",一个格式为"GB2312".所以在*作TXT文件之前,最好先确认一下该TXT文件的编*格式。
private String GetTxtCode(String path) // 获取text文件编*
{
String code = "";
code = "gb2312";
try {
InputStream is = new FileInputStream(path);
byte[] head = new byte[3];
try {
is.read(head);
if (head[0] == -1 && head[1] == -2)
code = "UTF-16";
if (head[0] == -2 && head[1] == -1)
code = "Unicode";
if (head[0] == -17 && head[1] == -69 && head[2] == -65)
code = "UTF-8";
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return code;
}
此时我们就可以将FileCode传入FileInputStream安全打开TXT文件。如果使用二维数组作为返回值读取文件的话,我们最好先读取文件行数以定义数组维度,方法示例如下:
public int GetLines(String fileName) throws IOException //获取文件行数以便建立数组维度
{
FileReader in = new FileReader(fileName);
LineNumberReader reader = new LineNumberReader(in);
String strLine = reader.readLine();
int totalLines = 0;
while (strLine != null) {
totalLines++;
strLine = reader.readLine();
}
reader.close();
in.close();
return totalLines;
}
然后读取文件信息,这里读取的文件每行四个信息块,以制表符为分隔符:
public String [][] GetInfo(String path) throws IOException, FileNotFoundException{
int Lines=this.GetLines(path);
String [][] s = new String[Lines][4];
File f = new File(path);
String code = GetTxtCode(path);
// System.out.println("Txt File Code:" + code);
if (f.isFile() && f.exists()) {
InputStreamReader sr = new InputStreamReader(
new FileInputStream(f), code);
BufferedReader bf = new BufferedReader(sr);
// bf.skip(1);
String line;
String[] lin=new String[4];
int i=0;
while ((line = bf.readLine()) != null) {
lin = line.split("");
s[i][0]=lin[0];
s[i][1]=lin[1];
s[i][2]=lin[2];
s[i][3]=lin[3];
i++;
}
}
return s;
}