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; public class CharsetTransform { public static void main(String[] args) throws CharacterCodingException { Charset cn = Charset.forName("GBK"); CharsetEncoder cnEncoder = cn.newEncoder(); CharsetDecoder cnDecoder = cn.newDecoder(); CharBuffer cbuff = CharBuffer.allocate(32); cbuff.put("良红"); cbuff.flip(); ByteBuffer bbuff = cnEncoder.encode(cbuff); for (var i =0; i < bbuff.capacity(); i++){ System.out.println(bbuff.get(i) + " "); } System.out.println(" " + cnDecoder.decode(bbuff)); } }
output:
-63 -68 -70 -20 良红