* 转换流概念及流程
* OutputStreamWriter(字符流通向字节流的桥梁)
* 1.程序中写入字符时 先使用转换流 根据转换流想查询的码表格式去查询
* 2.如果查的是GBk格式,那么一个中文字符就查到了两个字节的 字节编码
* 3.这个字节编码给到了构建转换流时 传入的字节流
* 4.通过这个字节流按字节写到文件中
* 转换流:可以查询对应的码表
*
* 默认UTF-8格式写的文件 拿到 windows系统读取
* windows默认使用GBK格式来读取文件 会出现乱码
* 转换流可以 根据你想要的编码格式 进行读写
* 读写时可以设置编码格式
两种创建转换流的构造方法
* 1.需要字节输出流(不传编码格式 默认使用的是系统的编码格式)
* 2.编码格式的名字 (UTF-8,GBK 不区分大小写)
public static void getUTF8() throws IOException { // 创建一个字节输出流 FileOutputStream fos = new FileOutputStream("/Users/lanou/Desktop/Test/UTF8.txt"); // 创建一个转换流 OutputStreamWriter osw = new OutputStreamWriter(fos); // 写文件 osw.write("春风十里"); // 注意:一般只关外层的 流就可以了 osw.close(); } public static void getGBK() throws IOException { // 创建一个字节输出流 FileOutputStream fos = new FileOutputStream("/Users/lanou/Desktop/Test/GBK.txt"); // 按GBK格式写入文件 OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK"); osw.write("春风十里"); osw.close(); }
转换流读取文件
// 按UTF-8格式读文件 public static void GetFileByUTF8() throws IOException { // 创建一个字节输入流 FileInputStream fis = new FileInputStream("/Users/lanou/Desktop/Test/UTF8.txt"); InputStreamReader isr = new InputStreamReader(fis); int len = 0; char[] c = new char[1024]; while ((len = isr.read(c)) != -1) { System.out.println(new String(c, 0, len)); } }