1. import java.io.UnsupportedEncodingException;
    2. import java.nio.charset.Charset;
    3. import java.util.Arrays;
    4. public class Test {
    5. public static void main(String[] args) throws UnsupportedEncodingException {
    6. char x = '编'; // char 占用两个字节 也就是16bit.
    7. // 获取JVM 默认字符集
    8. System.out.println(Charset.defaultCharset()); //UTF-8
    9. System.out.println(System.getProperty("file.encoding"));//UTF-8
    10. String str = "编";
    11. System.out.println("##字符串转换成byte数组");
    12. byte[] defaultByteArray = str.getBytes();
    13. byte[] gbkByteArray = str.getBytes("GBK");
    14. byte[] utfByteArray = str.getBytes("UTF-8");
    15. System.out.println("defaultByteArray:" + Arrays.toString(defaultByteArray)); //defaultByteArray:[-25, -68, -106]
    16. System.out.println("gbkByteArray:" + Arrays.toString(gbkByteArray)); //gbkByteArray:[-79, -32]
    17. System.out.println("utfByteArray:" + Arrays.toString(utfByteArray)); //utfByteArray:[-25, -68, -106]
    18. System.out.println("##byte数组转换成字符串");
    19. String defaultStr = new String(defaultByteArray); // utf-8 到 utf-8 没有问题
    20. String gbkStr = new String(defaultByteArray, "GBK"); // utf-8 到 gbk 即: [-25, -68, -106] 到 [-79, -32]
    21. String utfStr = new String(defaultByteArray, "UTF-8"); // utf-8 到 utf-8 没有问题
    22. System.out.println("defaultStr:" + defaultStr); // defaultStr:编
    23. System.out.println("gbkStr:" + gbkStr); // gbkStr:缂� 这里乱码的原因是gbk是两个字节表示
    24. System.out.println("utfStr:" + utfStr); // utfStr:编
    25. byte[] bytes = {-25, -68};
    26. System.out.println(new String(bytes, "GBK") ); // 缂
    27. }
    28. }