本文写于 13 年前(2013 年 7 月),部分内容可能已经过时。
package java.nio.charset;

public abstract class Charset implements Comparable<Charset>{

    private static volatile Charset defaultCharset;


    /**
     * Returns the default charset of this Java virtual machine.
     *
     * <p> The default charset is determined during virtual-machine startup and
     * typically depends upon the locale and charset of the underlying
     * operating system.
     *
     * @return  A charset object for the default charset
     *
     * @since 1.5
     */
    public static Charset defaultCharset() {
        if (defaultCharset == null) {
	    synchronized (Charset.class) {
		java.security.PrivilegedAction pa =
		    new GetPropertyAction("file.encoding");
		String csn = (String)AccessController.doPrivileged(pa);
		Charset cs = lookup(csn);
		if (cs != null)
		    defaultCharset = cs;
                else 
		    defaultCharset = forName("UTF-8");
            }
	}
	return defaultCharset;
    }

}

就是一个lazy-init的单例模式实现。另外,其实就是取自file.encoding环境变量,取不到,默认是”UTF-8”。

Tips 可以在eclipse中用Display View中,执行java语句:

System.getProperty("file.encoding");

非常实用的功能。

本文由 arganzheng 创作,采用 CC BY 4.0 许可协议。在保留原文作者、署名以及完整原文链接(https://arganzheng.life/jvm-encoding.html)的前提下,欢迎各种形式的转载、翻译或商业引用。


COMMENTS

评论存放在 GitHub Discussions, 用 GitHub 账号登录即可发表,支持 Markdown。 想针对正文某句话说?选中那段文字,点浮出的「评论」即可划线评论;觉得哪里写错了,发表时勾上「同时提交 Issue」。 有人回复你时 GitHub 会按你的通知设置发邮件,不用守在这里。

×