二.字符流
1.单个字符读取
public static void main(String[] args){
try {
InputStreamReader in = new InputStreamReader(
new FileInputStream("D:\\bf\\Desktop\\test.txt"), "UTF-8");
int n ;
while((n = in.read()) != -1){
System.out.print((char)n);
}
in.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
2.按行读取,利用BufferedReader对象提供的readLine()方法
public static void main(String[] args) {
BufferedReader reader=null;
try {
InputStreamReader read = new InputStreamReader(new FileInputStream("D:\\bf\\Desktop\\test.txt"), "UTF-8");
reader = new BufferedReader(read);
String line=null;
while((line =reader.readLine()) != null){
System.out.println(line);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (reader !=null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
InputStreamReader是一个一个字符读取的,每次读取都会执行一次IO,IO操作很浪费时间,这就导致程序效率降低,而BufferedReader可以一次读取大量的数据,大大减少了IO次数,提升效率。