Java字符串编解码

-Dfile.encoding=GBK

-Dfile.encoding解释:

在命令行中输入java,在给出的提示中会出现-D的说明:

-D<name>=<value>

               set a system property

-D后面需要跟一个键值对,作用是通过命令行向java虚拟机传递一项系统属性

对-Dfile.encoding=UTF-8来说就是设置系统属性file.encoding为UTF-8

那么file.encoding什么意思?字面意思为文件编码。

搜索java源码,只能找到4个文件中包含file.encoding的文件,也就是说只有四个文件调用了file.encoding这个属性。

在java.nio.charset包中的Charset.java中。这段话的意思说的很明确了,简单说就是默认字符集是在java虚拟机启动时决定的,依赖于java虚拟机所在的操作系统的区域以及字符集。

代码中可以看到,默认字符集就是从file.encoding这个属性中获取的。


获得file.encoding属性

@Test
public void test987() {
    System.out.println(System.getProperty("file.encoding"));
}


Java对字符串的编码

@Test
public void test987() throws UnsupportedEncodingException {
    System.out.println(System.getProperty("file.encoding"));// java默认编码是UTF-8
    /**
     * getBytes()方法的作用
     * Encodes this {String} into a sequence of bytes using the named
     * charset, storing the result into a new byte array.
     */

    String msg = "中文字符串";
    String utfMsg = new String(msg.getBytes("gbk"), "gbk");
    System.out.println(utfMsg);

    /**
     * 第二个参数的作用是
     * Constructs a new {String} by decoding the specified array of bytes
     * using the specified charset.
     */
    String msg2 = new String(msg.getBytes(), "utf-8");
    System.out.println(msg2);     // 乱码

    System.out.println(msg.getBytes("gbk").length);  //10
    System.out.println(msg.getBytes("utf-8").length);//15
    System.out.println(msg.getBytes("gb2312").length); //10
}

运行结果:

GBK

中文字符串

?????????

10

15

10


Process finished with exit code 0



你可能感兴趣的:(Java字符串编解码)