java 自定义BufferedReader
程序员文章站
2022-03-25 22:26:32
class MyBufferedReader { private FileReader r; public MyBufferedReader(FileReader r) { this.r = r; } //可以一次读一行数据的方法 public String myReadLine() throws ......
class mybufferedreader { private filereader r; public mybufferedreader(filereader r) { this.r = r; } //可以一次读一行数据的方法 public string myreadline() throws ioexception { //定义一个临时容器。原bufferedreader封装的是字符数组。 //我们定义一个stringbuild容器。因为最终还是要将数据变成字符串。 stringbuilder sb = new stringbuilder(); int ch = 0; while ((ch = r.read()) != -1) { if (ch == '\r') continue; if (ch == '\n') return sb.tostring(); else sb.append((char) (ch)); } if (sb.length() != 0) return sb.tostring(); return null; } public void myclose() throws ioexception { r.close(); } } public class mybufferedreaderdemo { public static void main(string[] args) throws ioexception { filereader fr = new filereader("buf.txt"); mybufferedreader mybuf = new mybufferedreader(fr); string line = null; while ((line = mybuf.myreadline()) != null) { system.out.println(line); } mybuf.myclose(); } }