CharArrayReader是字符数组输入流,CharArrayReader用于读取字符数组,继承于Reader操作的数据是以字符为单位。
(1)CharArrayReader实际上是通过字符数组去保存数据。
(2)在构造函数中有buf,我们通过buf来创建对象。
(3)read()函数是读取下一个字符

CharArrayReader主要的函数:
CharArrayReader(char[] buf)
CharArrayReader(char[] buf, int offset, int length)

void      close()
void      mark(int readLimit)
boolean   markSupported()
int       read()
int       read(char[] buffer, int offset, int len)
boolean   ready()
void      reset()
long      skip(long charCount)

示例代码:

public class CharArrayReaderTest {

    private static final int LEN = 5;
    // 对应英文字母“abcdefghijklmnopqrstuvwxyz”
    private static final char[] ArrayLetters = new char[] {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t',    'u','v','w','x','y','z'};

    public static void main(String[] args) {
        tesCharArrayReader() ;
    }

    /**
     * CharArrayReader的API测试函数
    */
    private static void tesCharArrayReader() {
        try {
            // 创建CharArrayReader字符流,内容是ArrayLetters数组
            CharArrayReader car = new CharArrayReader(ArrayLetters);

            // 从字符数组流中读取5个字符
            for (int i=0; i<LEN; i++) {
                // 若能继续读取下一个字符,则读取下一个字符
                if (car.ready() == true) {
                    // 读取“字符流的下一个字符”
                    char tmp = (char)car.read();
                    System.out.printf("%d : %c\n", i, tmp);
                }
            }

            // 若“该字符流”不支持标记功能,则直接退出
            if (!car.markSupported()) {
                System.out.println("make not supported!");
                return ;
            }

            // 标记“字符流中下一个被读取的位置”。即--标记“f”,因为因为前面已经读取了5个字符,所以下一个被读取的位置是第6个字符”
            // (01), CharArrayReader类的mark(0)函数中的“参数0”是没有实际意义的。
            // (02), mark()与reset()是配套的,reset()会将“字符流中下一个被读取的位置”重置为“mark()中所保存的位置”
            car.mark(0);

            // 跳过5个字符。跳过5个字符后,字符流中下一个被读取的值应该是“k”。
            car.skip(5);

            // 从字符流中读取5个数据。即读取“klmno”
            char[] buf = new char[LEN];
            car.read(buf, 0, LEN);
            System.out.printf("buf=%s\n", String.valueOf(buf));

            // 重置“字符流”:即,将“字符流中下一个被读取的位置”重置到“mark()所标记的位置”,即f。
            car.reset();
            // 从“重置后的字符流”中读取5个字符到buf中。即读取“fghij”
            car.read(buf, 0, LEN);
            System.out.printf("buf=%s\n", String.valueOf(buf));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
运行结果:
0 : a
1 : b
2 : c
3 : d
4 : e
buf=klmno
buf=fghij

基于JDK1.8的CharArrayReader源码分析:

public class CharArrayReader extends Reader {
    /** The character buffer. */
    //字符床缓冲数组
    protected char buf[];

    /** The current buffer position. */
    //当前位置
    protected int pos;

    /** The position of mark in buffer. */
    //标记位置
    protected int markedPos = 0;

    /**
     *  The index of the end of this buffer.  There is not valid
     *  data at or beyond this index.
     */
    //缓冲区使用的索引,超出这个索引无效
    protected int count;

    /**
     * Creates a CharArrayReader from the specified array of chars.
     * @param buf       Input buffer (not copied)
     */
    public CharArrayReader(char buf[]) {
        this.buf = buf;
        this.pos = 0;
        this.count = buf.length;
    }

    /**
     * Creates a CharArrayReader from the specified array of chars.
     *
     * <p> The resulting reader will start reading at the given
     * <tt>offset</tt>.  The total number of <tt>char</tt> values that can be
     * read from this reader will be either <tt>length</tt> or
     * <tt>buf.length-offset</tt>, whichever is smaller.
     *
     * @throws IllegalArgumentException
     *         If <tt>offset</tt> is negative or greater than
     *         <tt>buf.length</tt>, or if <tt>length</tt> is negative, or if
     *         the sum of these two values is negative.
     *
     * @param buf       Input buffer (not copied)
     * @param offset    Offset of the first char to read
     * @param length    Number of chars to read
     */
    public CharArrayReader(char buf[], int offset, int length) {
        if ((offset < 0) || (offset > buf.length) || (length < 0) ||((offset + length) < 0)) {
                    throw new IllegalArgumentException();
        }
        this.buf = buf;
        this.pos = offset;
        this.count = Math.min(offset + length, buf.length);
        this.markedPos = offset;
    }

    /** Checks to make sure that the stream has not been closed */
    private void ensureOpen() throws IOException {
        if (buf == null)
            throw new IOException("Stream closed");
    }
        //读单个字符
    public int read() throws IOException {
        synchronized (lock) {
            ensureOpen();
            if (pos >= count)
                return -1;
            else
                return buf[pos++];
        }
    }
    //读取数据并保存到b中,off其实位置,len是长度
    public int read(char b[], int off, int len) throws IOException {
        synchronized (lock) {
            ensureOpen();
            if ((off < 0) || (off > b.length) || (len < 0) ||((off + len) > b.length) || ((off + len) < 0)) {
                    throw new IndexOutOfBoundsException();
            } else if (len == 0) {
                return 0;
            }

            if (pos >= count) {
                return -1;
            }
            if (pos + len > count) {
                len = count - pos;
            }
            if (len <= 0) {
                return 0;
            }
            System.arraycopy(buf, pos, b, off, len);
            pos += len;
            return len;
        }
    }

    //跳过n个字符
    public long skip(long n) throws IOException {
        synchronized (lock) {
            ensureOpen();
            if (pos + n > count) {
                n = count - pos;
            }
            if (n < 0) {
                return 0;
            }
            pos += n;
            return n;
        }
    }
    //是否可读
    public boolean ready() throws IOException {
        synchronized (lock) {
            ensureOpen();
            return (count - pos) > 0;
        }
    }
    //是否支持标记
    public boolean markSupported() {
        return true;
    }

    //标记位置
    public void mark(int readAheadLimit) throws IOException {
        synchronized (lock) {
            ensureOpen();
            markedPos = pos;
        }
    }

    //重置,位置为最近一次标记的位置
    public void reset() throws IOException {
        synchronized (lock) {
            ensureOpen();
            pos = markedPos;
        }
    }
    //关闭资源,这边就是让字符数组为空
    public void close() {
        buf = null;
    }
}

Java-IO之CharArrayReader的更多相关文章

  1. 【java】内存流:java.io.ByteArrayInputStream、java.io.ByteArrayOutputStream、java.io.CharArrayReader、java.io.CharArrayWriter

    package 内存流; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java. ...

  2. java io系列18之 CharArrayReader(字符数组输入流)

    从本章开始,我们开始对java io中的“字符流”进行学习.首先,要学习的是CharArrayReader.学习时,我们先对CharArrayReader有个大致了解,然后深入了解一下它的源码,最后通 ...

  3. Java IO(十四) CharArrayReader 和 CharArrayWriter

    Java IO(十四) CharArrayReader 和 CharArrayWriter 一.介绍 CharArrayReader 和 CharArrayWriter 是字符数组输入流和字符数组输出 ...

  4. Java IO之字符流和文件

    前面的博文介绍了字节流,那字符流又是什么流?从字面意思上看,字节流是面向字节的流,字符流是针对unicode编码的字符流,字符的单位一般比字节大,字节可以处理任何数据类型,通常在处理文本文件内容时,字 ...

  5. [Java IO]03_字符流

    Java程序中,一个字符等于两个字节. Reader 和 Writer 两个就是专门用于操作字符流的类. Writer Writer是一个字符流的抽象类.  它的定义如下: public abstra ...

  6. Java: IO 学习小结

    源: 键盘 System.in 硬盘 FileStream 内存 ArrayStream 目的: 控制台 System.out 硬盘 FileStream 内存 ArrayStream 处理大文件或者 ...

  7. java io 流分类表

    Java输入/输出流体系中常用的流分类(表内容来自java疯狂讲义) 注:下表中带下划线的是抽象类,不能创建对象.粗体部分是节点流,其他就是常用的处理流. 流分类 使用分类 字节输入流 字节输出流 字 ...

  8. JAVA IO 字节流与字符流

    文章出自:听云博客 题主将以三个章节的篇幅来讲解JAVA IO的内容 . 第一节JAVA IO包的框架体系和源码分析,第二节,序列化反序列化和IO的设计模块,第三节异步IO. 本文是第一节.     ...

  9. Java IO流体系中常用的流分类

    Java输入/输出流体系中常用的流分类(表内容来自java疯狂讲义) 注:下表中带下划线的是抽象类,不能创建对象.粗体部分是节点流,其他就是常用的处理流. 流分类 使用分类 字节输入流 字节输出流 字 ...

  10. java io系列01之 "目录"

    java io 系列目录如下: 01. java io系列01之  "目录" 02. java io系列02之 ByteArrayInputStream的简介,源码分析和示例(包括 ...

随机推荐

  1. Unique-paths (动态规划)

    题目描述 A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below) ...

  2. A TensorBoard plugin for visualizing arbitrary tensors in a video as your network trains.Beholder是一个TensorBoard插件,用于在模型训练时查看视频帧。

    Beholder is a TensorBoard plugin for viewing frames of a video while your model trains. It comes wit ...

  3. Nginx+Tomca+Redis实现负载均衡、资源分离、session共享

    目标实现:Nginx作为负载均衡后端多Tomcat实例,通过Redis实现Session共享. 操作系统环境:CentOS 6.8 SSH:SecureCRT 其中 Nginx服务:80端口 Tomc ...

  4. 40. Combination Sum II(midum, backtrack, 重要)

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...

  5. Lintcode394 Coins in a Line solution 题解

    [题目描述] There are n coins in a line. Two players take turns to take one or two coins from right side ...

  6. sql 复习练习

          一.基础1.说明:创建数据库CREATE DATABASE database-name2.说明:删除数据库drop database dbname3.说明:备份sql server--- ...

  7. centos6.8下weblogic12c静默安装

    环境: centos6.8 无桌面环境 jdk1.7.0_25 关闭iptables.selinux 安装前准备: 1.新建weblogic用户,设置weblogic密码 useradd weblog ...

  8. C++笔记003:从一个小程序开始

      原创笔记,转载请注明出处! 点击[关注],关注也是一种美德~ 安装好VS2010后,从第一个小程序开始. 在学习C语言时,我首先输出了一个程序员非常熟悉的对这个世界的问候:hello world! ...

  9. MongoDB 删除文档

    ongoDB remove()函数是用来移除集合中的数据. MongoDB数据更新可以使用update()函数.在执行remove()函数前先执行find()命令来判断执行的条件是否正确,这是一个比较 ...

  10. JavaScript 注释

    JavaScript 注释可用于提高代码的可读性. JavaScript 注释 JavaScript 不会执行注释. 我们可以添加注释来对 JavaScript 进行解释,或者提高代码的可读性. 单行 ...