FileReader 缺点
调用 FileReader
的 read()
方法,立即从硬盘读取一个字节,这样效率低下
解决
使用 BufferedReader
读取 文本文件,有以下优点:
- 读取效率更高。调用
read()
方法时,一次读取8192
个字符到内存中 - 会方便些,可以 按行读取
例子
package stdfile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class StdBuffReader {
public static void main(String[] args) {
BufferedReader br=null;
FileReader fr=null;
File file=new File("d:/2测试.txt");
try{
fr=new FileReader(file);
br=new BufferedReader(fr);
// String line=br.readLine();
// while( line !=null){
// System.out.println(line);
// line=br.readLine();
// }
String line=null;
while ( (line=br.readLine()) !=null ){
System.out.println( line );
}
}catch(FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(br!=null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fr!=null){
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}