java IO核心类库梳理

2018-06-10  本文已影响0人  一路花开_8fab

以前每次使用java I/0类库时都要搜索,今天梳理了一下,把I/O核心类串了起来

流代表任何有能力产生数据的数据源对象或者是有能力接收数据的接收端对象。“流”屏蔽了IO设备中处理数据的细节。任何自InputStream或Reader派生而来的类都含有read()方法,用于读取单个字节或字节数组。同样,任何自OutputStream或Writer派生而来的类都含有write()方法,用于写取单个字节或字节数组。

1. InputStream/OutputStream继承结构仅支持8位字节流

在某些场合,面向字节的InputStream和OutputStream是合适的解决方案,比如java.util.zip就是面向字节而不是面向字符的。

2. Reader/Writer继承结构提供兼容Unicode与面向字符的I/O功能

3.InputStreamReader/OutputStreamWriter是字节流和字符流转换的桥梁

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.
An OutputStreamWriter is a bridge from character streams to byte streams:Characters written to it are encoded into bytes 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.

字节流和字符流转换需要提供编码格式(若不提供,由平台决定默认的编码格式),使用时需注意。

/**
     * 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) {
                String csn = AccessController.doPrivileged(
                    new GetPropertyAction("file.encoding"));
                Charset cs = lookup(csn);
                if (cs != null)
                    defaultCharset = cs;
                else
                    defaultCharset = forName("UTF-8");
            }
        }
        return defaultCharset;
    }
上一篇 下一篇

猜你喜欢

热点阅读