Java Reader read()方法

java.io.Reader.read(char[] cbuf,int off,int len) 将字符读入数组的一部分。该方法将阻塞,直到某些输入可用,发生I/O错误或到达流的末尾为止。

1 语法

public abstract int read(char[] cbuf,int off,int len)

2 参数

cbuf:目标缓冲区。

off:开始存储字符的偏移量。

len:要读取的最大字符数。

3 返回值

返回读取的字符数,如果已到达流的末尾,则返回-1。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.Reader.read(char[] cbuf,int off,int len)方法的例子
 */
import java.io.*;

public class Demo {
    public static void main(String[] args) {
        String s = "Hello world";

        // create a StringReader
        Reader reader = new StringReader(s);

        // create a char array to read chars into
        char cbuf[] = new char[5];

        try {
            // read characters into a portion of an array.
            System.out.println("" + reader.read(cbuf, 0, 5));

            // print cbuf
            System.out.println(cbuf);

            // close the stream
            reader.close();

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

输出结果为:

5
Hello

热门文章

优秀文章