java.io.Reader的相关方法的使用
欢迎各位朋友指正
public class Test_IO_Reader {
public static void main(String[] args) {
//设置3个字符的缓存区
CharBuffer cb = CharBuffer.allocate(3);
char[] c = new String("Hello World").toCharArray();
Reader car = new CharArrayReader(c);
try {
//开始处标记,读取超过20个字符,将不能reset
car.mark(20);
//读取3个字符到缓冲区
car.read(cb);
System.out.println("打印缓存区的字符串");
System.out.println(new String(cb.array()));
char ch;
System.out.println("继续读流");
while ((ch = (char) car.read()) != -1) {
System.out.println(ch);
//跳过一个字符
car.skip(1);
//是否可以保证下次read不阻塞
if (!car.ready()) {
break;
}
}
//重置该流,回到标记处
car.reset();
System.out.println("重置之后读流");
while ((ch = (char) car.read()) != -1) {
System.out.println(ch);
car.skip(1);
if (!car.ready()) {
break;
}
}
}catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果:
打印缓存区的字符串
Hel
继续读流
l
o
l
重置之后读流
H
l
o
W
r
d