JAVA基础知识之StringReader流

一、StringReader流定义

    API说明:字符串输入流、其本质就是字符串

二、StringReader的实例域

    //流对象
    private String str;
    
    //流的长度
    private int length;
    
    //流的当前位置,下个字符的索引
    private int next = 0;
    
    //流的标记位置
    private int mark = 0;

三、StringReader流构造函数

    /**
     * 利用字符串创建字符输入流
     */
    public StringReader(String s) {
        this.str = s;
        this.length = s.length();
    }

四、StringReader流的API

1)read(): 从流中读取单个字符,若到文件末尾则返回-1


    /**
     * 从流中读取单个字符,若到文件末尾则返回-1
     */
    public int read() throws IOException {
        synchronized (lock) {
            ensureOpen();
            if (next >= length)
                return -1;
            return str.charAt(next++);
        }
    }

2)read(char cbuf[], int off, int len):读取最多len个字节到目标数组中,从目标数组的下标off开始存储,返回实际读取的字节数

 /**
     * 读取最多len个字节到目标数组中,从目标数组的下标off开始存储,返回实际读取的字节数
     * @exception  IOException  If an I/O error occurs
     */
    public int read(char cbuf[], int off, int len) throws IOException {
        synchronized (lock) {
            ensureOpen();
            if ((off < 0) || (off > cbuf.length) || (len < 0) ||
                ((off + len) > cbuf.length) || ((off + len) < 0)) {
                throw new IndexOutOfBoundsException();
            } else if (len == 0) {
                return 0;
            }
            if (next >= length)
                return -1;
            int n = Math.min(length - next, len);
            str.getChars(next, next + n, cbuf, off);
            next += n;
            return n;
        }
    }

3)close() : 关闭流无效,关闭后调用该类其它方法会报异常


    /**
     * 关闭流无效,关闭后调用该类其它方法会报异常
     */
    public void close() {
        str = null;
    }

五、StringReader流的作用

    暂未使用故未知晓,故先了解功能

你可能感兴趣的:(JAVA基础知识之StringReader流)