Java 字符转码之UTF-8互转GBK

Java UTF-8转GBK详解

java跟python类似的做法,在java中字符串的编码是java修改过的一种Unicode编码,所以看到java中的字符串,心理要默念这个东西是java修改过的一种Unicode编码的编码。

package string;

import java.nio.charset.Charset;


public class UTF82GBK {

    public static void main(String[] args) throws Exception {
        //系统的默认编码是GBK
        System.out.println("Default Charset=" + Charset.defaultCharset());
        String t = "hfjkds中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国hfsdkj<img src=‘sasa‘ /> fjldsajflkdsjaflkdsjalf <img src=‘sada‘ ait=‘‘/>sfdsfadas";  
        //思路:先转为Unicode,然后转为GBK
        String utf8 = new String(t.getBytes( "UTF-8"));
        //等同于:
//        String utf8 = new String(t.getBytes( "UTF-8"),Charset.defaultCharset());
        
        System.out.println(utf8);  
        String unicode = new String(utf8.getBytes(),"UTF-8");   
        //等同于:
//        String unicode = new String(utf8.getBytes(Charset.defaultCharset()),"UTF-8");   
        System.out.println(unicode);  
        String gbk = new String(unicode.getBytes("GBK"));  
        //等同于:
//        String gbk = new String(unicode.getBytes("GBK"),Charset.defaultCharset());  
          
        System.out.println(gbk);  
    }

}
package com.mkyong;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
 
public class UTF8ToGBK {
    public static void main(String[] args) throws Exception {
 
        File fileDir = new File("/home/user/Desktop/Unsaved Document 1");
 
        BufferedReader in = new BufferedReader(new InputStreamReader(
                new FileInputStream(fileDir), "UTF-8"));
 
        String str;
 
        while ((str = in.readLine()) != null) {
            System.out.println(str);// java内部只有unicode编码 所以str是unicode编码
            String str2 = new String(str.getBytes("GBK"), "GBK");// str.getBytes("GBK")是gbk编码,但是str2是unicode编码
            System.out.println(str2);
        }
 
        in.close();
    }
}

 问题的关键是new String(xxx.getBytes(“gbk”), “gbk”)这句话是什么意思,xxx.getBytes(“gbk”)得到的数组编码是GBK,因此必须必须告诉java:我传给你的数组是gbk编码的,你在转换成你内部的编码的时候记得要进行一些处理,new String(xxx.getBytes(“gbk”), “gbk”),这句话第二个“gbk”是告诉java传递给它的是gbk编码的字符串。

String fullStr = new String(str.getBytes("UTF-8"), "UTF-8");//正常
String fullStr2 = new String(str.getBytes("UTF-8"), "GBK");//不正常,java内置的编码->utf8  被当成GBK编码转换成java内置的编码

看一下jdk文档是怎么说的

public String(byte[] bytes,
      Charset charset)

Constructs a new String by decoding the specified array of bytes using the specified charset.

那现在的问题就是,我怎么在String中持有GBK编码的东西呢?

String str3 = new String(str.getBytes("GBK"),"ISO-8859-1");
System.out.println(new String(str3.getBytes("ISO-8859-1"),"GBK"));

Java GBK转UTF-8详解

Java语言是一种编程语言,它是一个高级的、面向对象的、平台无关的语言。Java主要是用来构建Web应用程序,而在Java Web应用程序中将字符串编码变成UTF-8是非常有必要的。在本文中,我们将从多个方面详细探讨Java GBK转UTF-8。

一、转换原理

GBK编码和UTF-8编码是两种不同的编码格式。GBK编码是一种多字节编码方式,每个汉字占用两个字节存储,因此在文本处理中经常遇到GBK编码转UTF-8编码的需求。UTF-8编码是一种字符编码方式,与ASCII码兼容,可以支持从U+0000至U+10FFFF范围内的所有字符。

在Java程序中,字符串默认的编码方式是UTF-16编码,因此需要将GBK编码转换为UTF-8编码,主要是为了避免出现乱码的情况。通过Java的相关API来实现将GBK编码转换为UTF-8编码。

二、具体实现

1.使用InputStreamReader和OutputStreamWriter转换文件编码

    FileInputStream fileInputStream = new FileInputStream("gbk.txt");
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK");

    FileOutputStream fileOutputStream = new FileOutputStream("utf-8.txt");
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");

    int length = 0;
    char[] buffer = new char[1024];

    while ((length = inputStreamReader.read(buffer)) != -1) {
        outputStreamWriter.write(buffer, 0, length);
    }

    outputStreamWriter.close();
    fileOutputStream.close();
    inputStreamReader.close();
    fileInputStream.close();

上述代码中,先使用FileInputStream和InputStreamReader读取GB2312编码的文件,然后再使用FileOutputStream和OutputStreamWriter将文件以UTF-8编码写入到新的文件中。

2.使用String.getBytes()方法转换字符串编码

    String strGBK = "这是一段GBK编码的字符串";
    byte[] bytes = strGBK.getBytes("GBK");
    String strUTF = new String(bytes,"UTF-8");
    System.out.println(strUTF);

上述代码中,我们先定义了一个字符串strGBK,将其转换成字节数组bytes,并指定编码方式为GBK。接着,通过String构造方法将字节数组bytes以UTF-8编码方式构建新的字符串strUTF,并进行输出。

3.使用编码转换器Charset实现编码转换

    String strGBK = "这是一段GBK编码的字符串";
    Charset gbkCharset = Charset.forName("GBK");
    Charset utf8Charset = Charset.forName("UTF-8");
    ByteBuffer byteBuffer = gbkCharset .encode(strGBK);
    CharBuffer charBuffer = utf8Charset .decode(byteBuffer);
    System.out.println(charBuffer.toString());

上述代码中,我们首先定义一个字符串strGBK,然后通过Charset的forName方法分别创建GBK编码和UTF-8编码的Charset,并使用GBK编码器将字符串转换成ByteBuffer,再通过UTF-8解码器将ByteBuffer转换成CharBuffer,最后输出转换后的字符串。

三、注意事项

在进行GB2312到UTF-8编码转换时,需要注意以下几点:

1.文本文件编码格式

在Java程序中,使用FileInputStream、FileOutputStream、BufferedInputStream、BufferedOutputStream等类进行文件读写时,需要明确文件的编码格式,否则会出现乱码等问题。

2.源代码文件编码格式

为了保证源代码文件编码格式的一致性,最好将所有的源文件均保存为UTF-8编码,否则可能会出现编译错误等问题。

3.字符串编码格式

在Java程序中,如果需要将字符串从GBK编码转换成UTF-8编码,需要使用String的getBytes()方法,同时指定源编码和目标编码。

四、总结

本文详细介绍了Java GBK转UTF-8的具体实现方法,包括文件编码转换、字符串编码转换和使用字符集Charset实现编码转换。在进行GB2312到UTF-8编码转换时,需要注意文本文件编码格式、源代码文件编码格式和字符串编码格式的一致性。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年11月9日
下一篇 2023年11月9日

相关推荐