Java基础知识—File文件操作练习作业—06
6.自定义类实现缓冲字符流的功能
readLine()
class MyBufferedReader{
public String myReadLine(){
…;
}
}
import java.io.FileReader;
import java.util.ArrayList;
/**
*
* @author Fight_steven
*/
public class BufferedReader01 {
public static void main(String[] args) throws Exception {
String fileNmae = "C:\\test\\1.txt";
MyBufferedReader mbr = new MyBufferedReader(fileNmae);
System.out.println(mbr.myReadLine());
System.out.println(mbr.myReadLine());
}
}
class MyBufferedReader {
FileReader fr;
public MyBufferedReader(String fileName) throws Exception {
fr = new FileReader(fileName);
}
public String myReadLine() throws Exception {
StringBuilder sb = new StringBuilder();
ArrayList<Character> list = new ArrayList<>();
int flag = 0;
while (true) {
int pd = fr.read();
if (((char) pd == '\r') || ((char) pd == '\n')) {
break;
} else if (pd == -1) {
flag = -1;
break;
} else {
list.add((char) pd);
}
}
for (char c : list) {
sb.append(c);
}
if (flag == -1) {
return null;
}
return sb.toString();
}
}