Java字符串编码和转换操作

简介: 在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");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值