📄 safeinputstreamreader.java
字号:
import java.io.*;
public class SafeInputStreamReader extends Reader {
static final int BUF_SIZE = 1024;
byte[] buf = new byte[BUF_SIZE];
char[] chars;
int charsPos;
int bufPos;
String encoding;
public SafeInputStreamReader(InputStream stream, String encoding) throws UnsupportedEncodingException {
new String(new byte[]{}, encoding);
this.encoding = encoding;
this.stream = stream;
}
public int read(char[] cbuf, int off, int len) throws IOException {
if (chars != null) {
int tail = chars.length - charsPos;
if (tail <= len) {
System.arraycopy(chars, charsPos, cbuf, off, tail);
chars = null;
return tail;
} else {
System.arraycopy(chars, charsPos, cbuf, off, len);
charsPos += len;
return len;
}
}
int rc = stream.read(buf, bufPos, BUF_SIZE-bufPos);
if (rc > 0) {
bufPos += rc;
} else if (bufPos == 0) {
return -1;
}
int i = bufPos;
while (--i >= 0 && buf[i] != '\n');
if (i < 0) {
i = bufPos;
} else {
i += 1;
}
String s = new String(buf, 0, i, encoding);
bufPos -= i;
System.arraycopy(buf, i, buf, 0, bufPos);
char[] cb = s.toCharArray();
if (cb.length <= len) {
System.arraycopy(cb, 0, cbuf, off, cb.length);
return cb.length;
} else {
System.arraycopy(cb, 0, cbuf, off, len);
charsPos = len;
chars = cb;
return len;
}
}
public void close() throws IOException {
stream.close();
}
private InputStream stream;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -