NIO中的字符编码问题
程序员文章站
2024-02-22 16:04:10
...
获取所有编码
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class ChannelTest {
@Test
public void channel5() throws IOException {
Map<String, Charset> charsets = Charset.availableCharsets();
Set<Entry<String,Charset>> sets=charsets.entrySet();
for (Entry<String,Charset>entry:sets){
System.out.println(entry.getKey()+"="+entry.getValue());
}
}
}
编码与解码
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
public class ChannelTest {
@Test
public void channel6() throws IOException {
Charset cs1 = Charset.forName("GBK");
//获取编码器(上面设计了GBK)所以通过cs1设置编码默认就是GBK
CharsetEncoder ce=cs1.newEncoder();
//获取解码器
CharsetDecoder cd = cs1.newDecoder();
CharBuffer cBuf=CharBuffer.allocate(1024);
cBuf.put("你好java");
cBuf.flip();//切换成读取
//编码
ByteBuffer bBuf=ce.encode(cBuf);
for (int i = 0; i < 8; i++) {
System.out.println(bBuf.get());
}
bBuf.flip();
//解码
CharBuffer cBuf2 = cd.decode(bBuf);
System.out.println(cBuf2);
}
}