Java.io.FilterReader.read() 方法
描述
java.io.FilterReader.read(char[] cbuf, int off, int len) 方法将长度为 len 的字符读取到数组中,从偏移量 off 开始。
声明
以下是 java.io.FilterReader.read(char[] cbuf, int off, int len) 方法的声明 −
public int read(char[] cbuf, int off, int len)
参数
cbuf − 目标缓冲区。
off − 开始存储字符的偏移量。
len − 要读取的字符数。
返回值
此方法返回要读取的字符数,如果到达流的末尾,则返回 -1。
异常
IOException − 如果发生 I/O 错误。
示例
下面的例子展示了 java.io.FilterReader.read(char[] cbuf, int off, int len) 方法的使用。
package com.tutorialspoint;
import java.io.FilterReader;
import java.io.Reader;
import java.io.StringReader;
public class FilterReaderDemo {
public static void main(String[] args) throws Exception {
FilterReader fr = null;
Reader r = null;
char[] cbuf = new char[6];
int i = 0;
try {
// create new reader
r = new StringReader("ABCDEF");
// create new filter reader
fr = new FilterReader(r) {
};
// read data of len 4, to the buffer
i = fr.read(cbuf, 2, 4);
System.out.println("No. of characters read: "+i);
// read till the end of the char buffer
for(char c:cbuf) {
// checks for the empty character in buffer
if((byte)c == 0)
c = '-';
// prints
System.out.print(c);
}
} catch(Exception e) {
// if any I/O error occurs
e.printStackTrace();
} finally {
// releases system resources associated with this stream
if(r!=null)
r.close();
if(fr!=null)
fr.close();
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
No. of characters read: 4 --ABCD

