Java字符串编码和转换操作

来源:互联网 发布:江苏省建筑节能数据库 编辑:程序博客网 时间:2024/06/06 01:42

简介: 在java程序的class里,字符串以utf-8编码保存。在程序处理中,需要进行字符串编码转换时,使用getByte指定编码。

在java程序中,定义的字符串,在class文件中,字符串是以utf-8进行保存的。

public class Hello1 {    public static void main(String [] args) {        System.out.println("aaaa长风aaaa");    }}

编译后,在class文件内,保存的字符串如下:
这里写图片描述

这里字符[长]的utf8-的编码:0xE995BF; [风]的utf8-的编码:0xE9A38E;

  1. 创建String时指定charset字符编码
    使用String(byte bytes[], String charsetName)构造字符串。字节数组必须是charsetName指定的编码。

    Constructs a new String by decoding the specified array of bytes using the specified charset. 
  2. String根据编码要求进行转换
    要进行字符串编码转换,先使用String.getBytes(String charsetName) 获取到指定编码的字节数组,然后通过该数组在进行处理。

说明:

String.getBytes(String charsetName) throws UnsupportedEncodingExceptionEncodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.

在java 1.7中,新加入了StandardCharsets类,专门用来标示字符编码

public final class StandardCharsets {    public static final Charset US_ASCII = Charset.forName("US-ASCII");    public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");    public static final Charset UTF_8 = Charset.forName("UTF-8");    public static final Charset UTF_16BE = Charset.forName("UTF-16BE");    public static final Charset UTF_16LE = Charset.forName("UTF-16LE");    public static final Charset UTF_16 = Charset.forName("UTF-16");}
0 0
原创粉丝点击