一,Charset
1,字符集
-编码:字符串---字节数组
-解码:字节数组---字符串
package com.momo.demo;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
/*
- Charset中的编码和解码
- 编码器:
- CharsetEncoder newEncoder() 为此字符集构造一个新的编码器。
- 解码器:
- CharsetDecoder newDecoder() 为此字符集构造一个新的解码器。
- /
public class Demo1 {public static void main(String[] args) throws CharacterCodingException {// SortedMap keys = map.keySet();for (String key : keys) {Charset value = map.get(key);System.out.println(key+"--"+value);}// Set> entries = map.entrySet();
for (Map.Entry entry : entries) {
System.out.println(entry.getKey()+"--"+entry.getValue());
}*/
Charset cs = Charset.forName("GBK"); //获取编码器 CharsetEncoder ce = cs.newEncoder(); //获取解码器 CharsetDecoder cd = cs.newDecoder(); CharBuffer buf = CharBuffer.allocate(1024); buf.put("默默真帅"); buf.flip(); //编码 ByteBuffer buf2 = ce.encode(buf); for (int i = 0; i < 8; i++) { System.out.println(buf2.get()); } //解码 buf2.flip(); CharBuffer buf3 = cd.decode(buf2); System.out.println(buf3); System.out.println("-----------------"); Charset cs2 = Charset.forName("UTF8"); buf2.flip(); CharBuffer cb2 = cs2.decode(buf2); System.out.println(cb2);
}
}
标签:buf2,java,nio,Charset,字符集,System,import From: https://blog.51cto.com/u_16230968/7175867