利用转换流将GBK格式文件以UTF-8输出

时间:2023-01-06 13:16:43
  3.利用转换流将GBK格式文件以UTF-8输出
   
   解题思路:
      1,InputStreamReader(File file,"gbk");读入文件
      2,OutputStreamReder(File file,"utf-8"); 写入文件
      3,验证上面的是否正确,就用 "utf-8" "gbk" 格式
         分别读取一次文件 
          InputStreamReader(File file,"utf-8")
         InputStreamReader(File file,"gbk")
          如果文件里面的中文用"utf-8" 读取不乱码

                     而用"gbk"  读取出来的乱码,那就转换成功了!


我写的代码如下:

package HomeWork3;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;


public class GBKtoUTF {
	public static void main(String[] args) throws IOException {
		InputStreamReader isr = new InputStreamReader(new FileInputStream("g:\\gbk.txt"), "gbk");
		OutputStreamWriter isw = new OutputStreamWriter(new FileOutputStream("h:\\utf.txt"), "utf-8");
		int len = 0;
		while ((len = isr.read()) != -1) {
			isw.write(len);
		}
		isw.close();
		isr.close();
	}
}


测试是否乱码 代码如下:

package HomeWork3;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test_CodeFormat {
	public static void main(String[] args) throws IOException {

		// 创建自己输入流,传递文本文件
		FileInputStream fis = new FileInputStream("h:\\utf.txt");
		// 创建转换流对象, 构造方法,包装字节输入流
		InputStreamReader isr = new InputStreamReader(fis, "utf-8");
		char[] ch = new char[1024];
		int len = isr.read(ch);
		System.out.println(new String(ch, 0, len));
		isr.close();
	}
}