从本章开始,我们开始对java io中的“字符流”进行学习。首先,要学习的是CharArrayReader。学习时,我们先对CharArrayReader有个大致了解,然后深入了解一下它的源码,最后通过示例来掌握它的用法。
转载请注明出处:http://www.cnblogs.com/skywang12345/p/io_18.html
CharArrayReader 介绍
CharArrayReader 是字符数组输入流。它和ByteArrayInputStream类似,只不过ByteArrayInputStream是字节数组输入流,而CharArray是字符数组输入流。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)
1 package java.io;
2
3 public abstract class Reader implements Readable, Closeable {
4
5 protected Object lock;
6
7 protected Reader() {
8 this.lock = this;
9 }
10
11 protected Reader(Object lock) {
12 if (lock == null) {
13 throw new NullPointerException();
14 }
15 this.lock = lock;
16 }
17
18 public int read(java.nio.CharBuffer target) throws IOException {
19 int len = target.remaining();
20 char[] cbuf = new char[len];
21 int n = read(cbuf, 0, len);
22 if (n > 0)
23 target.put(cbuf, 0, n);
24 return n;
25 }
26
27 public int read() throws IOException {
28 char cb[] = new char[1];
29 if (read(cb, 0, 1) == -1)
30 return -1;
31 else
32 return cb[0];
33 }
34
35 public int read(char cbuf[]) throws IOException {
36 return read(cbuf, 0, cbuf.length);
37 }
38
39 abstract public int read(char cbuf[], int off, int len) throws IOException;
40
41 private static final int maxSkipBufferSize = 8192;
42
43 private char skipBuffer[] = null;
44
45 public long skip(long n) throws IOException {
46 if (n < 0L)
47 throw new IllegalArgumentException("skip value is negative");
48 int nn = (int) Math.min(n, maxSkipBufferSize);
49 synchronized (lock) {
50 if ((skipBuffer == null) || (skipBuffer.length < nn))
51 skipBuffer = new char[nn];
52 long r = n;
53 while (r > 0) {
54 int nc = read(skipBuffer, 0, (int)Math.min(r, nn));
55 if (nc == -1)
56 break;
57 r -= nc;
58 }
59 return n - r;
60 }
61 }
62
63 public boolean ready() throws IOException {
64 return false;
65 }
66
67 public boolean markSupported() {
68 return false;
69 }
70
71 public void mark(int readAheadLimit) throws IOException {
72 throw new IOException("mark() not supported");
73 }
74
75 public void reset() throws IOException {
76 throw new IOException("reset() not supported");
77 }
78
79 abstract public void close() throws IOException;
80 }