2010年4月10日 星期六

Encoding and decoding

對 input stream 內容進行解碼 (decoding) 要用到類別: Charset. input stream 所讀進來的內容為 bytes, 要解碼成不同的格式(如 utf8), 便要用類別 Charset,及 CharsetDecoder


類別的使用

使用 forName(String charsetName) 方法取得一個 Charset物件。 可以使用的 charsetName 有:

Charset
Description
US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set
ISO-8859-1   ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
UTF-8 Eight-bit UCS Transformation Format
UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order
UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order
UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark

取得 Charset 物件後, 要建立一個新的解碼器物件。使用方法

abstract  CharsetDecoder newDecoder()
          Constructs a new decoder for this charset.

傳回一個 CharsetDecoder 物件。之後,使用 CharsetDecoder 物件的 decode() 方法:

CharBuffer decode(ByteBuffer in)
          Convenience method that decodes the remaining content of a single input byte buffer into a newly-allocated character buffer.





進行解碼,解碼的結果會儲存在一個 CharBuffer 物件。注意, 此 decode() 方法需要一個 ByteBuffer 物件。

Code Example:

// read, decode, and parse xml content (UTF-8 encoded!)
        byte[] xml = new byte[len];
        is.read(xml);
        ByteBuffer buf = ByteBuffer.wrap(xml);    // 將 byte[]  包裝成 ByteBuffer
       Charset charset = Charset.forName("UTF-8");   // 取得 Charset 物件
        CharsetDecoder decoder = charset.newDecoder();  // 取得 Decoder
        CharBuffer charBuffer = decoder.decode(buf);   // 進行 解碼
     

沒有留言: