JAVA基础知识指导:TXT文件详解
单单读取TXT文件的话,用BufferedReader效率比较高,也方便一些。需要注意的是,TXT文件在不同版本的操作系统中编码格式会有所不同,笔者曾经试过在两台同样的WIN7系统下,一个格式为"UTF-8",一个格式为"GB2312".所以在操作TXT文件之前,最好先确认一下该TXT文件的编码格式。view plaincopyprint?
01.????private String GetTxtCode(String path) // 获取text文件编码
02. {
03. String code = "";
04. code = "gb2312";
05. try {
06. InputStream is = new FileInputStream(path);
07. byte[] head = new byte;
08. try {
09. is.read(head);
10.
11. if (head == -1 && head == -2)
12. code = "UTF-16";
13. if (head == -2 && head == -1)
14. code = "Unicode";
15. if (head == -17 && head == -69 && head == -65)
16. code = "UTF-8";
17. } catch (IOException e) {
18.
19. e.printStackTrace();
20. }
21. } catch (FileNotFoundException e) {
22.
23. e.printStackTrace();
24. }
JAVA基础知识指导:TXT文件详解
25.26. return code;
27. }
????private String GetTxtCode(String path) // 获取text文件编码
{
String code = "";
code = "gb2312";
try {
InputStream is = new FileInputStream(path);
byte[] head = new byte;
try {
is.read(head);
if (head == -1 && head == -2)
code = "UTF-16";
if (head == -2 && head == -1)
code = "Unicode";
if (head == -17 && head == -69 && head == -65)
code = "UTF-8";
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return code;
}
此时我们就可以将FileCode传入FileInputStream安全打开TXT文件。如果使用二维数组作为返回值读取文件的话,我们最好先读取文件行数以定义数组维度,方法示例如下:
view plaincopyprint?
01.public int GetLines(String fileName) throws IOException //获取文件行数以便建立数组维度
02. {
03. FileReader in = new FileReader(fileName);
04. LineNumberReader reader = new LineNumberReader(in);
05. String strLine = reader.readLine();
06. int totalLines = 0;
07. while (strLine != null) {
08. totalLines++;
JAVA基础知识指导:TXT文件详解
09. strLine = reader.readLine();10. }
11. reader.close();
12. in.close();
13. return totalLines;
14.
15. }
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;
}
然后读取文件信息,这里读取的文件每行四个信息块,以制表符为分隔符:
view plaincopyprint?
01.public String [][] GetInfo(String path) throws IOException, FileNotFoundException{
02.
03. int Lines=this.GetLines(path);
04. String [][] s = new String;
05. File f = new File(path);
06.
07. String code = GetTxtCode(path);
08.// System.out.println("Txt File Code:" + code);
09. if (f.isFile() && f.exists()) {
10. InputStreamReader sr = new InputStreamReader(
11. new FileInputStream(f), code);
12. BufferedReader bf = new BufferedReader(sr);
13.// bf.skip(1);
14. String line;
15. String[] lin=new String;
16. int i=0;
JAVA基础知识指导:TXT文件详解
17. while ((line = bf.readLine()) != null) {18. lin = line.split("");
19.
20. s=lin;
21. s=lin;
22. s=lin;
23. s=lin;
24. i++;
25.
26. }
27.
28.
29. }
30. return s;
31. }
页:
[1]