【java】Charset 字符集,字符串转 Unicode 字符串

前言

  • jdk8

实例化字符集

Charset charset = Charset.forName("utf8");

StandardCharsets 字符集常量

Charset charset = StandardCharsets.UTF_8;

在这里插入图片描述

查看字符集名称与别名

import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class TestMain {

	public static void main(String[] args) {
		Charset charset = Charset.forName("utf16");
        System.out.println("字符集名称:" + charset.name());
        
        System.out.println("字符集别名:");
        Set<String> set = charset.aliases();
        Iterator<String> it = set.iterator();
        it.forEachRemaining(name -> {
        	System.out.println("- " + name);
        });
	}
}

执行结果:

字符集名称:UTF-16
字符集别名:
- UTF_16
- unicode
- utf16
- UnicodeBig

字符集名称与别名

字符集名称 字符集别名
UTF-16
  • UTF_16
  • unicode
  • utf16
  • UnicodeBig
UTF-8
  • unicode-1-1-utf-8
  • UTF8
GBK
  • CP936
  • windows-936
ISO-8859-1
  • 819
  • ISO8859-1
  • l1
  • ISO_8859-1:1987
  • ISO_8859-1
  • 8859_1
  • iso-ir-100
  • latin1
  • cp819
  • ISO8859_1
  • IBM819
  • ISO_8859_1
  • IBM-819
  • csISOLatin1

字符串转 Unicode 字符串

字符串:{"name":"类别"}
转 Unicode 字符串:{"name":"\u7c7b\u522b"}

    /**
     * 字符串转换unicode
     */
    public static String string2Unicode(String string) {
    	StringBuffer unicode = new StringBuffer();
    	for (int i = 0; i < string.length(); i++) {
            // 取出每一个字符
    		char c = string.charAt(i);
    		if (c<0x20 || c>0x7E) {
    			// 转换为unicode
    			String tmp = Integer.toHexString(c);
    			if (tmp.length() >= 4) {
    				unicode.append("\\u" + Integer.toHexString(c));
    			} else if (tmp.length() == 3){
    				unicode.append("\\u0" + Integer.toHexString(c));
    			} else if (tmp.length() == 2){
    				unicode.append("\\u00" + Integer.toHexString(c));
    			} else if (tmp.length() == 1){
    				unicode.append("\\u000" + Integer.toHexString(c));
    			} else if (tmp.length() == 3){
    				unicode.append("\\u0000");
    			}
    		} else {
    			unicode.append(c);
    		}
        }
        return unicode.toString();
    }
  • 注意 1:Unicode 长度不足 4 位时,要左补 0。比如 ·,不左补 0 时得到 \ub7,但期望值应是 \u00b7
    在这里插入图片描述
    在这里插入图片描述
  • 注意 2:ascii 码表(完整的 ascii 码表 0~255)低 128 部分中,第 32(十六进制:20)个开始至第 126(十六进制:7E)个结束,为可显示字符。可显示字符是否转换成 Unicode 视情况而定。我这个需求里,ascii 码表中可显示字符不需要转码。

参考

Java 中 16 进制与字符串之间的相互转换
Unicode 在线转换

 

posted @ 2024-06-27 10:13  CharyGao  阅读(99)  评论(0)    收藏  举报