InputStreamReader 是字节流通向字符流的桥梁:它使用指定的 charset 读取字节并将其解码为字符。它使用的字符集可以由名称指定或显式给定,或者可以接受平台默认的字符集。转换流是一种处理流,可以在字节流和字符流之间转换,同时可设置转换编码
package com.mike.io.eg;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
/**
* @author mike
* @date 2020-11-26
* @desc 字节输入转换流
*/
public class InputStreamReaderDemo {
public static void main(String[] args) {
//定义转换流
BufferedReader br = null;
//定义文件对象
File file = new File("F:\foo.txt");
try {
//创建转换流
br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8")); //将文本转换为utf-8字符
String data;
while((data = br.readLine()) != null) {
System.out.println(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.mike.io.eg;
import java.io.*;
/**
* @author mike
* @date 2020-11-26
* @desc 字节输出转换流
*/
public class OutputStreamWriterDemo {
public static void main(String[] args) {
//定义转换流
BufferedWriter bw = null;
//定义文件对象
File file = new File("F:\foo.txt");
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
bw.write("我的名字叫mike");
System.out.println("写入成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}