計算機只認識01數字,要轉換成可供閱讀的字符,需要對底層的01串按一定規則進行解析,這個規則就是各種編碼,如ASCII,UTF-8等等。
01串----解碼(decode)----->字符
字符----編碼(encode)----->01串
用什么樣的編碼方式存儲,就得用相應的解碼方式解碼才能不出現亂碼。
示例:
1public class Convert {
2public static void main(String args[]) {
3System.out.println(Charset.availableCharsets());
4Charset asciiCharset = Charset.forName("US-ASCII");
5CharsetDecoder decoder = asciiCharset.newDecoder();
6byte help[] = { 72, 101, 108, 112 };
7ByteBuffer asciiBytes = ByteBuffer.wrap(help);
8CharBuffer helpChars = null;
9try {
10helpChars = decoder.decode(asciiBytes);
11} catch (CharacterCodingException e) {
12System.err.println("Error decoding");
13System.exit(-1);
14}
15System.out.println(helpChars);
16Charset utfCharset = Charset.forName("UTF-16LE");
17CharsetEncoder encoder = utfCharset.newEncoder();
18ByteBuffer utfBytes = null;
19try {
20utfBytes = encoder.encode(helpChars);
21} catch (CharacterCodingException e) {
22System.err.println("Error encoding");
23System.exit(-1);
24}
25byte newHelp[] = utfBytes.array();
26for (int i = 0, n = newHelp.length; i < n; i++) {
27System.out.println(i + " :" + newHelp[i]);
28}
29}
30}
31
"" (developerWorks,2002年10月)專門討論字符集(特別是轉換和編碼模式)。