public class TransStreamDemo {
public static void main(String[] args) throws IOException {
//OutputStreamWriter 是字符流通向字节流的桥梁:可使用指定的charset将要写入流中的字符编码成字节
//作用:将字符串按照指定的编码表转成字节,再使用字节流将这些字节写出去
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("tempfile/u8cn.ext"), StandardCharsets.UTF_8);
osw.write("你好");
osw.close();
}
}
OutputStreamWriter和InputStreamReader
OutputStreamWriter和InputStreamReader是字符和字节的桥梁:可称之为字符转换流
原理:字节流+编码表
FileWriter和FileReader
FileWriter和FileReader作为子类,仅作为操作字符文件的便捷类存在.
当操作的字符文件,使用的是默认编码表时可以不用父类.而直接用子类就完成操作.
InputStreamReader isr = new InputStreamReader(new FileInputStream("a.txt"));//默认字符集
InputStreamReader isr = new InputStreamReader(new FileInputStream("a.txt"),"GBK");//指定GBK字符集
FileReader fr = new FileReader("a.txt");
这三句代码的功能是一样的,其中第三句最为便捷
注意:一但要指定其他编码时,绝对不能用子类,必须使用字符转换流.
什么时候用子类呢?
条件:
1.操作的是文件.
2.使用默认编码