将JDK默认编码设置为UTF-8

时间:2023-01-05 10:47:01

此博文非原创:参考小兵qwer   https://blog.csdn.net/xiaobing_122613/article/details/70209716

只是想留下对自己有用的东西,同时帮助更多人。


1.先检查本地JDK编码:

代码:

import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Default Charset=" + Charset.defaultCharset());
        System.out.println("file.encoding=" + System.getProperty("file.encoding"));
        System.out.println("Default Charset=" + Charset.defaultCharset());
        System.out.println("Default Charset in Use=" + getDefaultCharSet());
    }

    private static String getDefaultCharSet() {
        OutputStreamWriter writer = new OutputStreamWriter(new ByteArrayOutputStream());
        String enc = writer.getEncoding();
        return enc;
    }

}

编译运行:

将JDK默认编码设置为UTF-8

创建系统环境变量:

变量名: JAVA_TOOL_OPTIONS, 变量值:-Dfile.encoding=UTF-8

将JDK默认编码设置为UTF-8

退出cmd再编译运行HelloWorld

将JDK默认编码设置为UTF-8

显示默认的编码已经改变为UTF-8