GBK编码字节流与UTF-8编码字节流的转换

Posted abtious

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了GBK编码字节流与UTF-8编码字节流的转换相关的知识,希望对你有一定的参考价值。

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class BianMaDemo4 {
    public static void main(String[] args) throws IOException, FileNotFoundException {
        
        /*
         * 
         * GBK编码字节流与UTF-8编码字节流的转换:
         * 操作步骤就是:先解码:new String(src,0,len,"GBK")得到字符串;再使用getBytes("UTF-8")得到UTF-8编码字节数组        
         */
        
        //gbk-->utf-8
        FileInputStream fis=new FileInputStream("gbk_file.txt");//gbk文件
        FileOutputStream fos=new FileOutputStream("222.txt");//utf-8文件
        byte[] src=new byte[1024];
        int len;
        byte[] dest;
        while((len=fis.read(src))!=-1){
            dest=new String(src,0,len,"GBK").getBytes("UTF-8");
            fos.write(dest,0,dest.length );
        }
        
        
        //utf-8-->gbk
        /*FileInputStream fis=new FileInputStream("222.txt");//utf-8文件
        FileOutputStream fos=new FileOutputStream("gbk_file.txt");//gbk文件
        byte[] src=new byte[1024];
        int len;
        byte[] dest;
        while((len=fis.read(src))!=-1){
            dest=new String(src,0,len,"UTF-8").getBytes("GBK");
            fos.write(dest);
        }*/

        fis.close();//释放资源
        fos.close();
        
    }

}

 

以上是关于GBK编码字节流与UTF-8编码字节流的转换的主要内容,如果未能解决你的问题,请参考以下文章

字节流与字符流的区别

java细节笔记(9月16)

流--Stream

IO流

数据读写API——IO流

计算机中的编码和字符集:理解二进制字节流和常见编码方案