二.字元流
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();
}
}
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZwpmL5EjMzETOzcTM4ADOwkTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
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次數,提升效率。