• xj111
    2019-07-31
    老师,懂了,看了printWriter的实现,理解了你说的就像是“俄罗斯套娃”这句话,谢谢!

    作者回复: 这门课里我管它叫做俄罗斯套娃模式,这种套路的官方真名叫做装饰者模式

    
    
  • xj111
    2019-07-31
    老师,昨天听完你的I/O这节课,理解的写入流程就是:用printWriter给程序里写入字符串,但是写到目标文件里需要为byte,每次写入byte都非常麻烦,所有需要OutputStreamWriter完成char字符型到byte的转化,最终通过FileOutputStream写入到目标文件中;
    但是我在网上看的资料可以直接用PrintWriter类给目标文件写入内容,如下:
    PrintWriter pw = new PrintWriter(file);
    pw.println("这是一个测试文件");
    我昨天试了下内容是写到了文件里,所以没有理解可以直接用PrintWriter写入内容,为什么还要加上OutputStreamWriter、FileOutputStream?
    展开

    作者回复: new PrintWriter(file)的代码是:

        public PrintWriter(File file) throws FileNotFoundException {
            this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
                 false);
        }


    Look at 上面的 new OutputStreamWriter,这种简化的方式下,JDK把这个OutputStreamWriter给create 好了。

    PS:查看代码的方式是按住ctrl/command(for mac),鼠标单击。

    
    
我们在线,来聊聊吧