IO学习BufferedWriter 规格严格

今天无意见看SNMP4J的代码时候,突然间看到同事写的一个测试代码,BufferedWriter,说实话写了2年代码,Java写了不少,C写了不少,可是总忘。你看,今天遇见这个了,唉,我还用的真少,一般都是用PrintWriter封装一下。于是决定晚上回家仔细看看,到家吃了老婆做的面条,饭饱后,打开Eclipse,看看BufferedWriter源代码,很简洁也很清晰,但是我用BufferedWriter调用writer写字符,写到文件里面后,发现字符编码是GBK的。咳咳,那必须的啊,我机器是XP中文环境,但是一般BufferedWriter不都是用OutputStreamWriter封装一下的么,嗯,我用的是FileWriter作为参数,于是跟进,看看默认的FileWriter代码,果真构造函数里面创造了一个Out Writer,并且编码格式没有指定,默认是null了,因为我也没指定。

构造函数里面调用了Sun内部的StreamEncoder类,于是。。。。继续跟进,打开以前下载的OpenJDK代码,继续看,啊哈,找到这个代码了,各位请看:

    // Factories for java.io.OutputStreamWriter
    public static StreamEncoder forOutputStreamWriter(OutputStream out,
                                                      Object lock,
                                                      String charsetName)
        throws UnsupportedEncodingException
    {
        String csn = charsetName;
        if (csn == null)
            csn = Charset.defaultCharset().name();
        try {
            if (Charset.isSupported(csn))
                return new StreamEncoder(out, lock, Charset.forName(csn));
        } catch (IllegalCharsetNameException x) { }
        throw new UnsupportedEncodingException (csn);
    }

这是OutputStreamWriter中的代码:

        try {
            se = StreamEncoder.forOutputStreamWriter(out, this, (String)null);
        } catch (UnsupportedEncodingException e) {
            throw new Error(e);
        }

这回大家看明白了,默认不传的时候,调用Charset.defaultCharset(),再看看这个方法怎么实现的:

    public static Charset defaultCharset() {
        if (defaultCharset == null) {
            synchronized (Charset.class) {
                String csn = AccessController.doPrivileged(
                    new GetPropertyAction("file.encoding"));
                Charset cs = lookup(csn);
                if (cs != null)
                    defaultCharset = cs;
                else
                    defaultCharset = forName("UTF-8");
            }
        }
        return defaultCharset;
    }

OK,调用系统属性了,看来我系统默认属性就是GBK了。再往下查看lookup和forName,目前就没什么驱动力让我继续看了。

我也属于一知半解型,附带3张IO的图片,我觉得画的不错

/Files/diyunpeng/1.gif

/Files/diyunpeng/2.gif

/Files/diyunpeng/3.gif

原文地址:https://www.cnblogs.com/diyunpeng/p/2420117.html