Java IO类学习总结

2017-05-26  本文已影响0人  测试你个头

刚好在看深入Java web技术内幕这本书,书里提到了Java IO,之前日常的工作中一直对各种IO类之间的关系理不清楚,正好趁此机会走读下源码做下总结

IO类

人类识别字符,机器识别字节,如果需要对字符进行机器间的传输,需要将字符向字节进行转化,Java针对2种数据格式,有不同的IO类:

InputStream/Reader/InputStreamReader3者之间的关系:

1.InputStreamReader是字节流和字符流之间的桥梁,InputStreamReader继承了Reader类,InputStreamReader的注释如下:
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified {@link java.nio.charset.Charset charset}. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.

2.更直白的理解:InputStreamReader将InputStream中读取的字节转换为字符,下面的代码将3者关系表现了出来:

        // 创建字节输入流
        FileInputStream fi = new FileInputStream("/Users/ali/10_python/get-pip.py");

        // 字节输入流向字符输入流转换
        InputStreamReader ir = new InputStreamReader(fi, "UTF-8");

        // 从InputStreamReader中读取到BufferedReader,实现高效的字符行读取
        BufferedReader br = new BufferedReader(ir);

        StringBuilder contentBuffer = new StringBuilder();
        String line = "";
        while ((line = br.readLine()) != null) {
            contentBuffer.append(line);
            System.out.println(line);
        }
上一篇下一篇

猜你喜欢

热点阅读