1 package com.itheima.demo03.ReverseStream; 2 3 import java.io.*; 4 5 /* 6 练习:转换文件编码 7 将GBK编码的文本文件,转换为UTF-8编码的文本文件。 8 9 分析: 10 1.创建InputStreamReader对象,构造方法中传递字节输入流和指定的编码表名称GBK 11 2.创建OutputStreamWriter对象,构造方法中传递字节输出流和指定的编码表名称UTF-8 12 3.使用InputStreamReader对象中的方法read读取文件 13 4.使用OutputStreamWriter对象中的方法write,把读取的数据写入到文件中 14 5.释放资源 15 */ 16 public class Demo04Test { 17 public static void main(String[] args) throws IOException { 18 //1.创建InputStreamReader对象,构造方法中传递字节输入流和指定的编码表名称GBK 19 InputStreamReader isr = new InputStreamReader(new FileInputStream("10_IO\\我是GBK格式的文本.txt"),"GBK"); 20 //2.创建OutputStreamWriter对象,构造方法中传递字节输出流和指定的编码表名称UTF-8 21 OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("10_IO\\我是utf_8格式的文件.txt"),"UTF-8"); 22 //3.使用InputStreamReader对象中的方法read读取文件 23 int len = 0; 24 while((len = isr.read())!=-1){ 25 //4.使用OutputStreamWriter对象中的方法write,把读取的数据写入到文件中 26 osw.write(len); 27 } 28 //5.释放资源 29 osw.close(); 30 isr.close(); 31 } 32 }
package com.yhqtv.demo06.trycatch; import java.io.*; /* * @author XMKJ yhqtv.com Email:yhqtv@qq.com * @create 2020-05-13-14:36 * */ public class Demo03InputStreamReader { public static void main(String[] args) throws IOException { InputStreamReader isr = new InputStreamReader(new FileInputStream("C:\\1.txt"), "GBK"); OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("C:\\2.txt"),"UTF-8"); int len; while ((len = isr.read()) != -1) { osw.write(len); } isr.close(); osw.close(); } }
原文:https://www.cnblogs.com/yhqtv-com/p/12884045.html