NIO Charset类字符编码对象

Charset类字符编码对象


介绍

java中使用Charset来表示编码对象

This class defines methods for creating decoders and encoders and for retrieving the various names associated with a charset.   
Instances of this class are immutable.


This class also defines static methods for testing whether a particular charset is supported, 
for locating charset instances by name, and for constructing a map that contains every charset  
for which support is available in the current Java virtual machine.

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

Charset常用静态方法

public static Charset forName(String charsetName)//通过编码类型获得Charset对象
public static SortedMap<String,Charset> availableCharsets()//获得系统支持的所有编码方式
public static Charset defaultCharset()//获得虚拟机默认的编码方式
public static boolean isSupported(String charsetName)//判断是否支持该编码类型

 
 
  • 1
  • 2
  • 3
  • 4
  • 5

Charset常用普通方法

public final String name()//获得Charset对象的编码类型(String)
public abstract CharsetEncoder newEncoder()//获得编码器对象
public abstract CharsetDecoder newDecoder()//获得解码器对象
. . . 还有很多方法

 
 
  • 1
  • 2
  • 3
  • 4
  • 5

Charset应用案列

获得本机支持的所有编码方式

public void testGetAvailableCharsets() {

    // 获得本机所有编码格式
    Map<String, Charset> charsets = Charset.availableCharsets();
    // 迭代遍历出编码方式
    for (Entry<String, Charset> entry : charsets.entrySet()) {
        System.out.println(entry.getKey() + " : " + entry.getValue().name());
    }

}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

获得JVM虚拟机默认编码方式

// 获得JVM默认编码方式
Charset charset=Charset.defaultCharset();

 
 
  • 1
  • 2
  • 3

使用编码器和解码器进行字符编码和解码

public void testEncoderAndDecoder() throws Exception{

    //使用Charset进行编码和解码
    CharsetEncoder encoder=Charset.forName("GBK").newEncoder();
    CharsetDecoder decoder=Charset.forName("GBK").newDecoder();

    ByteBuffer byteBuffer=encoder.encode(CharBuffer.wrap("中国编码".toCharArray()));

    CharBuffer charBuffer=decoder.decode(byteBuffer);
    String string=charBuffer.toString();

    System.out.println(string);

}

备注:写编码方式时候最好使用全大写字符比如:UTF-8、GBK。通常情况下大小写都能识别

备注:java中关于字符编码问题,通常借助String构造方法或URLEncoder/URLDecoder,或则使用Charset的编码器和解码器。

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19


ASCII :7Bit 来表示一个字符,共计可以表示128中字符。
ISO-8859-1:8Bit 表示一个字符,即用一个字节(byte)来表示一个字符,攻击可以表示256个字符。
gb2312 :两个字节表示一个汉字

unicode 是一种编码方式 采用两个字节来表示一个字符
UTF-16LE ,UTF15-BE
UTF-8,通过3个 字节来表示一个中文
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值