package com.guo.test.bufferedReader;
import java.io.IOException;
import java.io.Reader;
public class GuoBufferedReader {
public Reader reader;
private char[] bs = new char[1024];
private int index;
private int count;
public GuoBufferedReader(Reader reader) {
this.reader = reader;
}
public int read() throws IOException {
if (count == 0) {
count = reader.read(bs);
index = 0;
}
if (count == -1) {
return -1;
}
char c = bs[index];
index++;
count--;
return c;
}
public String readLine() throws IOException {
StringBuilder stringBuilder = new StringBuilder();
int c = -1;
while ((c = read()) != -1) {
if ('\r' == c) {
//这里判断下一个字符是不是\n,而是直接continue
continue;
} else if ('\n' == c) {
//遇到换行符,直接return。不能写break,有可能遇到空行,这时stringbuilder.length=0,但是不能返回null
return stringBuilder.toString();
} else {
stringBuilder.append((char) c);
}
}
//没有遇到换行符,但是到文件了,需要用到这里的判断
if (stringBuilder.length() > 0) {
return stringBuilder.toString();
}
return null;
}
public void close() throws IOException {
reader.close();
}
}
自定义bufferedreader
最新推荐文章于 2022-05-26 14:46:18 发布