NIO Charset类字符编码对象

来源:互联网 发布:杭州淘宝运营学徒招聘 编辑:程序博客网 时间:2024/06/04 18:59

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个 字节来表示一个中文