5 Java IO:InputStreamReader 和 OutputStreamWriter
阿新 • • 發佈:2019-02-07
1 java.io.InputStreamReader
InputStreamReader 將位元組輸入流 InputStream 轉換成字元流。
示例:
@Test
public void test() throws IOException {
try (
InputStream inputStream = new FileInputStream("D:/test.txt");
Reader reader = new InputStreamReader(inputStream);
) {
int data = reader.read();
while (data != -1) {
System.out.println((char) data);
data = reader.read();
}
}
}
執行結果:將測試檔案【D:/test.txt】中的英文字元逐一打印出來
G
o
o
d
n
e
w
s
!
以上示例列印了檔案中的英文字元,以下示例如何列印中文字元:
@Test
public void test() throws IOException {
try (
InputStream inputStream = new FileInputStream("D:/測試.txt" );
Reader reader = new InputStreamReader(inputStream, "GB2312");
) {
int data = reader.read();
while (data != -1) {
System.out.println((char) data);
data = reader.read();
}
}
}
執行結果:
好
消
息
!
可見,如果想列印中文字元需要在構造 InputStreamReader 物件時指定字元編碼,InputStreamReader 物件的 read() 方法一次讀取 2 個位元組大小的字元,GB2312 編碼每個中文字元正好佔用 2 個位元組,所以可以正常打印出來(參看 常見編碼佔用位元組數),但是 UTF-8 編碼中一箇中文字元對應 3 個位元組,思考如何列印 UTF-8 編碼的中文字元。
2 java.io.OutputStreamWriter
OutputStreamWriter 將位元組輸出流 OutputStream 轉換成字元流。
示例: