概述
InputStreamReader
InputStreamReader可以将字节流转为字符流,
构造函数
public InputStreamReader(InputStream in) {
//设置对象锁
super(in);
try {
//确定解码格式,分配缓冲区
sd = StreamDecoder.forInputStreamReader(in, this, (String)null);
} catch (UnsupportedEncodingException e) {
// The default encoding should always be available
throw new Error(e);
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
读取字符
public int read() throws IOException {
return read0();
}
private int read0() throws IOException {
synchronized (lock) {
// Return the leftover char, if there is one
if (haveLeftoverChar) {
haveLeftoverChar = false;
return leftoverChar;
}
//这里一次读取两个字符
char cb[] = new char[2];
int n = read(cb, 0, 2);
switch (n) {
case -1:
return -1;
case 2:
//读取到两个字符,保存第二个,
leftoverChar = cb[1];
haveLeftoverChar = true;
case 1:
//返回第一个字符
return cb[0];
default:
assert false : n;
return -1;
}
}
}
public int read(char cbuf[], int offset, int length) throws IOException {
int off = offset;
int len = length;
synchronized (lock) {
ensureOpen();
if ((off < 0) || (off > cbuf.length) || (len < 0) ||
((off + len) > cbuf.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
if (len == 0)
return 0;
int n = 0;
//如果有之前的剩余字符未读取
if (haveLeftoverChar) {
// 拷贝到数组
cbuf[off] = leftoverChar;
off++; len--;
haveLeftoverChar = false;
n = 1;
//读完了,返回
if ((len == 0) || !implReady())
return n;
}
//还需要读取一个字符
if (len == 1) {
int c = read0();
if (c == -1)
return (n == 0) ? -1 : n;
cbuf[off] = (char)c;
return n + 1;
}
//读取off+len个字符,以off为头,拷贝过去
return n + implRead(cbuf, off, off + len);
}
}
int implRead(char[] cbuf, int off, int end) throws IOException {
assert (end - off > 1);
//包装cbuf字符数组
CharBuffer cb = CharBuffer.wrap(cbuf, off, end - off);
if (cb.position() != 0)
// Ensure that cb[0] == cbuf[off]
cb = cb.slice();
boolean eof = false;
for (;;) {
//进行字节流到字符流的解码
CoderResult cr = decoder.decode(bb, cb, eof);
if (cr.isUnderflow()) {
if (eof)
break;
if (!cb.hasRemaining())
break;
if ((cb.position() > 0) && !inReady())
break; // Block at most once
int n = readBytes();
if (n < 0) {
eof = true;
if ((cb.position() == 0) && (!bb.hasRemaining()))
break;
decoder.reset();
}
continue;
}
if (cr.isOverflow()) {
assert cb.position() > 0;
break;
}
cr.throwException();
}
if (eof) {
// ## Need to flush decoder
decoder.reset();
}
if (cb.position() == 0) {
if (eof)
return -1;
assert false;
}
return cb.position();
}
最后
以上就是陶醉魔镜为你收集整理的InputStreamReaderInputStreamReader的全部内容,希望文章能够帮你解决InputStreamReaderInputStreamReader所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复