码迷,mamicode.com
首页 > 编程语言 > 详细

Java字符串编码和转换操作

时间:2016-05-12 17:29:48      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

简介: 在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 UnsupportedEncodingException

Encodes 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");
}

Java字符串编码和转换操作

标签:

原文地址:http://blog.csdn.net/whereismatrix/article/details/51363563

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!