- import java.io.FileReader;
- import java.io.IOException;
- public class MyBufferedReaderTest {
- public static void main(String[] args) throws IOException {
- MyBufferedReader mbr = new MyBufferedReader(new FileReader("Copy.txt"));
- String line = null;
- while ((line = mbr.readLine()) != null) {
- System.out.println(line);
- }
- mbr.close();
- }
- }
复制代码- import java.io.IOException;
- import java.io.Reader;
- /*
- * 模拟BufferedReader的readLine(),close()方法。
- */
- public class MyBufferedReader {
- private Reader r;
- private int count;
- public MyBufferedReader(Reader r) {
- this.r = r;
- }
- // 模拟readLine
- public String readLine() throws IOException {
- int ch = 0;
- // 定义一个容器
- StringBuilder sb = new StringBuilder();
- while ((ch = r.read()) != -1) {
- if (ch == '\r') {
- continue;
- }
- if (ch == '\n') {
- return ++count+sb.toString(); //haha0.toString(); haha0
- } else {
- //如果你不是\r,也不是\n,那么就把数据保存起来
- sb.append((char)ch); //haha9
- }
- }
-
- //判断sb里面是否还有数据
- if(sb.length()>0){
- return ++count+sb.toString();
- }
-
- return null;
- }
- // 模拟close方法
- public void close() throws IOException {
- r.close();
- }
- }
复制代码 为什么在目标文件最后几行全是空行时候会少读一行,如果最后一行不是空白就不会有这种问题?不知道我哪里出问题了 |
|