自定义BufferedReader,模拟readLine方法
import java.io.FileReader;
import java.io.IOException;
class MyBufferedReader {
private FileReader fileReader;
public MyBufferedReader(FileReader fileReader) {
this.fileReader = fileReader;
}
public String myReadLine() throws IOException {
StringBuilder builder = new StringBuilder();
int ch;
while ((ch = fileReader.read()) != -1) {
if (ch == '\r') {
continue;
}
if (ch == '\n') {
return builder.toString();
} else {
builder.append((char) ch);
}
}
if (builder.length() != 0) {
return builder.toString();
}
return null;
}
public void myClose() throws IOException {
fileReader.close();
}
}
public class MyBufferedReaderDemo {
public static void main(String[] args) throws Exception {
FileReader fileReader = new FileReader("E:\\demo.txt");
MyBufferedReader myBufferedReader = new MyBufferedReader(fileReader);
String line;
if ((line = myBufferedReader.myReadLine()) != null) {
System.out.println(line);
}
myBufferedReader.myClose();
}
}
网友评论