那么這篇博客我們講的是字符輸入輸出流:Reader、Writer(下圖紅色長方形框內),紅色橢圓框內是其典型實現,圖片顯示錯誤(FileReader、FileWriter)

①、為什么要使用字符流?
因為使用字節流操作漢字或特殊符號語言的時候容易亂碼,因為漢字不止一個字節,為了解決這個問題,建議使用字符流。
②、什么情況下使用字符流?
一般可以用記事本打開的文件,我們可以看到內容不亂碼的。就是文本文件,可以使用字符流。而操作二進制文件(比如圖片、音頻、視頻)必須使用字節流
1、字符輸出流:FileWriter
|
1
2
3
|
public
abstract
class
Writer
extends
Object
implements
Appendable, Closeable, Flushable
|
用於寫入字符流的抽象類
方法摘要:

下面我們用 字符輸出流 Writer 的典型實現 FileWriter 來介紹這個類的用法:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
//1、創建源
File srcFile =
new
File(
"io"
+File.separator+
"a.txt"
);
//2、創建字符輸出流對象
Writer out =
new
FileWriter(srcFile);
//3、具體的 IO 操作
/***
* void write(int c):向外寫出一個字符
* void write(char[] buffer):向外寫出多個字符 buffer
* void write(char[] buffer,int off,int len):把 buffer 數組中從索引 off 開始到 len個長度的數據寫出去
* void write(String str):向外寫出一個字符串
*/
//void write(int c):向外寫出一個字符
out.write(
65
);
//將 A 寫入 a.txt 文件中
//void write(char[] buffer):向外寫出多個字符 buffer
out.write(
"Aa帥鍋"
.toCharArray());
//將 Aa帥鍋 寫入 a.txt 文件中
//void write(char[] buffer,int off,int len)
out.write(
"Aa帥鍋"
.toCharArray(),
0
,
2
);
//將 Aa 寫入a.txt文件中
//void write(String str):向外寫出一個字符串
out.write(
"Aa帥鍋"
);
//將 Aa帥鍋 寫入 a.txt 文件中
//4、關閉流資源
/***
* 注意如果這里有一個 緩沖的概念,如果寫入文件的數據沒有達到緩沖的數組長度,那么數據是不會寫入到文件中的
* 解決辦法:手動刷新緩沖區 flush()
* 或者直接調用 close() 方法,這個方法會默認刷新緩沖區
*/
out.flush();
out.close();
|
2、字符輸入流:Reader
|
1
2
3
|
public
abstract
class
Reader
extends
Object
implements
Readable, Closeable
|
用於讀取字符流的抽象類。
方法摘要:

下面我們用 字符輸入流 Reader 的典型實現 FileReader 來介紹這個類的用法:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
//1、創建源
File srcFile =
new
File(
"io"
+File.separator+
"a.txt"
);
//2、創建字符輸出流對象
Reader in =
new
FileReader(srcFile);
//3、具體的 IO 操作
/***
* int read():每次讀取一個字符,讀到最后返回 -1
* int read(char[] buffer):將字符讀進字符數組,返回結果為讀取的字符數
* int read(char[] buffer,int off,int len):將讀取的字符存儲進字符數組 buffer,返回結果為讀取的字符數,從索引 off 開始,長度為 len
*
*/
//int read():每次讀取一個字符,讀到最后返回 -1
int
len = -
1
;
//定義當前讀取字符的數量
while
((len = in.read())!=-
1
){
//打印 a.txt 文件中所有內容
System.out.print((
char
)len);
}
//int read(char[] buffer):將字符讀進字符數組
char
[] buffer =
new
char
[
10
];
//每次讀取 10 個字符
while
((len=in.read(buffer))!=-
1
){
System.out.println(
new
String(buffer,
0
,len));
}
//int read(char[] buffer,int off,int len)
while
((len=in.read(buffer,
0
,
10
))!=-
1
){
System.out.println(
new
String(buffer,
0
,len));
}
//4、關閉流資源
in.close();
|
3、用字符流完成文件的復制
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
/**
* 將 a.txt 文件 復制到 b.txt 中
*/
//1、創建源和目標
File srcFile =
new
File(
"io"
+File.separator+
"a.txt"
);
File descFile =
new
File(
"io"
+File.separator+
"b.txt"
);
//2、創建字符輸入輸出流對象
Reader in =
new
FileReader(srcFile);
Writer out =
new
FileWriter(descFile);
//3、讀取和寫入操作
char
[] buffer =
new
char
[
10
];
//創建一個容量為 10 的字符數組,存儲已經讀取的數據
int
len = -
1
;
//表示已經讀取了多少個字節,如果是 -1,表示已經讀取到文件的末尾
while
((len=in.read(buffer))!=-
1
){
out.write(buffer,
0
, len);
}
//4、關閉流資源
out.close();
in.close();
|
