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

本文摘抄至 : skywang12345

摘要 : 介绍了 CharArrayReader 其API 的函数意思,和通过示例介绍了大致的使用。注意 : 当 car使用了 close 之后,它会清空 buf。 从此 car 不可再操作。这里和ByteArrayInputStream 不一样。

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

CharArrayReader 介绍


CharArrayReader 是 字符数组输入流 它和 ByteArrayInputStream 类似,只不过 ByteArrayInputStream 是 字节数组输入流 ,而CharArrayReader 是 字符数组输入流 。CharArrayReader 是用于读取字符数组,它继承与 Reader。 操作的数据是以字符为单位 !

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)

Reader和CharArrayReader源码分析


Reader是CharArrayReader的父类,我们先看看Reader的源码,然后再学CharArrayReader的源码。

1. Reader源码分析(基于jdk1.7.40)

package java.io;

public abstract class Reader implements Readable, Closeable {

    /**用于同步针对此流的操作的对象。 */
    protected Object lock;

    // 创建一个新的字符流 reader,其重要部分将同步其自身的 reader。
    protected Reader() {
        this.lock = this;
    }

    //创建一个新的字符流 reader,其重要部分将同步给定的对象。 
    protected Reader(Object lock) {
        if (lock == null) {
            throw new NullPointerException();
        }
        this.lock = lock;
    }

    public int read(java.nio.CharBuffer target) throws IOException {
        int len = target.remaining();
        char[] cbuf = new char[len];
        int n = read(cbuf, 0, len);
        if (n > 0)
            target.put(cbuf, 0, n);
        return n;
    }

    public int read() throws IOException {
        char cb[] = new char[1];
        if (read(cb, 0, 1) == -1)
            return -1;
        else
            return cb[0];
    }

    public int read(char cbuf[]) throws IOException {
        return read(cbuf, 0, cbuf.length);
    }
     //抽象类:将字符读取到下标从off开始、len个后续位置的cbuf中。 
     abstract public int read(char cbuf[], int off, int len) throws IOException;

    private static final int maxSkipBufferSize = 8192;

    private char skipBuffer[] = null;

    public long skip(long n) throws IOException {
        if (n < 0L)
            throw new IllegalArgumentException("skip value is negative");
        int nn = (int) Math.min(n, maxSkipBufferSize);
        synchronized (lock) {
            if ((skipBuffer == null) || (skipBuffer.length < nn))
                skipBuffer = new char[nn];
            long r = n;
            while (r > 0) {
                int nc = read(skipBuffer, 0, (int)Math.min(r, nn));
                if (nc == -1)
                    break;
                r -= nc;
            }
            return n - r;
        }
    }

    /** 检测此流是否可读*/  
    public boolean ready() throws IOException {
        return false;
    }

    public boolean markSupported() {
        return false;
    }

    public void mark(int readAheadLimit) throws IOException {
        throw new IOException("mark() not supported");
    }

    public void reset() throws IOException {
        throw new IOException("reset() not supported");
    }

    abstract public void close() throws IOException;

}

2. CharArrayReader 源码分析(基于jdk1.7.40)

package java.io;

public class CharArrayReader extends Reader {

    //字符数组缓冲
    protected char buf[];

    //下一个被获取的字符位置
    protected int pos;

    //被标记的位置
    protected int markedPos = 0;

    //字符缓冲的长度
    protected int count;

    //构造函数
    public CharArrayReader(char buf[]) {
        this.buf = buf;
        this.pos = 0;
        this.count = buf.length;
    }

    //构造函数
    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;
    }

    //判断“CharArrayReader”是否有效
    //若字符缓冲为 null,则认为其 无效
    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;
        }

    //判断“是否能读取下一个字符”。可以的话,返回 true,反之亦然。
    public boolean ready() throws IOException {
        synchronized (lock) {
            ensureOpen();
            return (count - pos) > 0;
        }
    }

    public boolean markSupported() {
        return true;
    }

    //保存当前位置,readAheadLimit在此处没有任何意义
    //mark()必须个 reset()配套使用。才有意义。
    public void mark(int readAheadLimit) throws IOException {
        synchronized (lock) {
            ensureOpen();
            markedPos = pos;
        }
    }

    //重置“下一个读取位置”为“mark”所标记的位置
    public void reset() throws IOException {
        synchronized (lock) {
            ensureOpen();
            pos = markedPos;
        }
    }

    //关闭 流,清空 buf,这里和 ByteArrayInputStream不一样
    public void close() {
        buf = null;
    }

}

说明:

CharArrayReader实际上是通过 “字符数组”去保存数据 。

  1. 通过 CharArrayReader(char[] buf)或 CharArrayReader(char[] buf,int offset,int lenght),我们可以根据 buf数组来创建 CharArrayReader 对象
  2. read()的作用还是从CharArrayReader中“读取一个字符”
  3. read(char[] buffer,int offset,int len)的作用是从CharArrayReader读取字符数据,并写入到字符数组 buffer中。offset是将字符写入到buffer的其实位置,len是写入的字符长度。
  4. markSupport()是判断CharArrayReader是否支持“标记的功能”他始终返回true。
  5. mark(int readlimit)的作用是记录标记的位置。记录标记的位置之后。某一时刻调用reset()则将“CharArrayReader下一个被读取的位置“重置到”mark(int readlimit)所标记的位置”;
    也就是说,reset()之后再读取CharArrayReader时,是从mark(int readlimit)所标记的位置开始读取。

示例代码


关于CharArrayReader中API的详细用法,参考示例代码(CharArrayReaderTest.java):

    public static void main(String[] args) {

        tesCharArrayReader() ;
    }

    private static void tesCharArrayReader() {
        // 创建CharArrayReader字符流,内容是ArrayLetters数组
        CharArrayReader car = new  CharArrayReader(ArrayLetters) ;

        try {
            // 从字符数组流中读取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 (Exception e) {
            e.printStackTrace();
        }
    }

}

运行结果:

0 : a
1 : b
2 : c
3 : d
4 : e
buf=klmno
buf=fghij

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值