字符流是針對字符數(shù)據(jù)的特點進行過優(yōu)化的,因而提供一些面向字符的有用特性,字符流的源或目標通常是文本文件。 Reader和Writer是java.io包中所有字符流的父類。由于它們都是抽象類,所以應(yīng)使用它們的子類來創(chuàng)建實體對象,利用對象來處理相關(guān)的讀寫操作。Reader和Writer的子類又可以分為兩大類:一類用來從數(shù)據(jù)源讀入數(shù)據(jù)或往目的地寫出數(shù)據(jù)(稱為節(jié)點流),另一類對數(shù)據(jù)執(zhí)行某種處理(稱為處理流)。
面向字符的輸入流類都是Reader的子類,其類層次結(jié)構(gòu)如圖所示。
下表列出了 Reader 的主要子類及說明。
Reader 所提供的方法則如這張表所示,可以利用這些方法來獲得流內(nèi)的位數(shù)據(jù):
使用 FileReader 類讀取文件
FileReader 類是 Reader 子類 InputStreamReader 類的子類,因此 FileReader 類既可以使用Reader 類的方法也可以使用 InputStreamReader 類的方法來創(chuàng)建對象。
在使用 FileReader 類讀取文件時,必須先調(diào)用 FileReader()構(gòu)造方法創(chuàng)建 FileReader 類的對象,再調(diào)用 read()方法。FileReader 構(gòu)造方法的格式為:
1
|
public FileReader(String name); //根據(jù)文件名創(chuàng)建一個可讀取的輸入流對象 |
【例】利用 FileReader 類讀取純文本文件的內(nèi)容
1
2
3
4
5
6
7
8
9
10
11
|
import java.io.*; class ep10_1{ public static void main(String args[]) throws IOException{ char a[]= new char [ 1000 ]; //創(chuàng)建可容納 1000 個字符的數(shù)組 FileReader b= new FileReader( "ep10_1.txt" ); int num=b.read(a); //將數(shù)據(jù)讀入到數(shù)組 a 中,并返回字符數(shù) String str= new String(a, 0 ,num); //將字符串數(shù)組轉(zhuǎn)換成字符串 System.out.println( "讀取的字符個數(shù)為:" +num+ ",內(nèi)容為:\n" ); System.out.println(str); } } |
需要注意的是,Java 把一個漢字或英文字母作為一個字符對待,回車或換行作為兩個字符對待。
使用 BufferedReader 類讀取文件
BufferedReader 類是用來讀取緩沖區(qū)中的數(shù)據(jù)。使用時必須創(chuàng)建 FileReader 類對象,再以該對象為參數(shù)創(chuàng)建 BufferedReader 類的對象。BufferedReader 類有兩個構(gòu)造方法,其格式為:
1
2
|
public BufferedReader(Reader in); //創(chuàng)建緩沖區(qū)字符輸入流 public BufferedReader(Reader in, int size); //創(chuàng)建輸入流并設(shè)置緩沖區(qū)大小 |
【例】利用 BufferedReader 類讀取純文本文件的內(nèi)容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import java.io.*; class ep10_2{ public static void main(String args[]) throws IOException{ String OneLine; int count= 0 ; try { FileReader a= new FileReader( "ep10_1.txt" ); BufferedReader b= new BufferedReader(a); while ((OneLine=b.readLine())!= null ){ //每次讀取 1 行 count++; //計算讀取的行數(shù) System.out.println(OneLine); } System.out.println( "\n 共讀取了" +count+ "行" ); b.close(); } catch (IOException io){ System.out.println( "出錯了!" +io); } } } |
需要注意的是,執(zhí)行 read()或 write()方法時,可能由于 IO 錯誤,系統(tǒng)拋出 IOException 異常,需要將執(zhí)行讀寫操作的語句包括在 try 塊中,并通過相應(yīng)的 catch 塊來處理可能產(chǎn)生的異常。