Java NIO之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.

Charset常用静态方法

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

Charset常用普通方法

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

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());
    }

}

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

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

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

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的编码器和解码器。

总结

编码和解码问题是所有程序员都会面临的问题,尤其是对于非英语系国家的程序员更是如此。只有理解清楚字符编码原理才能在今后程序开发过程即使遇到编码问题也能够处之泰然。

备注:备注计算机只能识别二进制数字,因此如果想要让计算机识别出自然语言文字自然就需要存在一张二进制数字和自然语言的映射表。每次编码和解码时都要查询这张映射表。

举例:

假如使用GBK码表对"中"字编码结果是183(十进制表示)
如果你使用UTF-8码表来解码的话,查出来的183对应的是"国"字。
结果就是错的了,所以编码和解码对应的码表一定要相同才能够解码正确(除非码表之间有包含关系,比如UTF-8已经包含了ASCII码表,那么解码就没问题)

参考

1、https://en.wikipedia.org/wiki/Character_encoding
2、http://www.ruanyifeng.com/blog/2010/02/url_encoding.html
3、http://www.ruanyifeng.com/blog/2007/10/ascii_unicode_and_utf-8.html
4、http://polaris.blog.51cto.com/1146394/377468/

猜你喜欢

转载自www.cnblogs.com/shamo89/p/9095541.html