今天刚学缓冲区,在自己编写MyBufferedReader 时,在使用myReadLine()时,总是不能督导最后一行,求大神们指点。
程序如下:
package Buffered;import java.io.FileReader;
import java.io.IOException;public class MyBufferedReader {

private FileReader fr;
private char []buf = new char[1024];
private int count = 0;
private int pos = 0;
public MyBufferedReader(FileReader f){
this.fr = f;
}
public int myRead() throws IOException{
if(count == 0){
count = fr.read(buf);
pos = 0;
}
if(count<0)
return -1;
int ch = buf[pos++];
count--;
return ch; 
}

public String myReadLine() throws IOException{
StringBuilder sb = new StringBuilder();
int ch = 0;
while ((ch = myRead()) != -1) {
if (ch == '\r')
continue;
if (ch == '\n')
return sb.toString();
sb.append((char) ch);
}
return null;
}
public void myClose() throws IOException {
fr.close();
}}============================================================================
package IOtest;import java.io.FileReader;
import java.io.IOException;import Buffered.MyBufferedReader;public class MyBufferedReaderTest { public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("C:\\demo.txt");
MyBufferedReader mbw = new MyBufferedReader(fr);
String line = null;
while((line = mbw.myReadLine()) != null){
System.out.println(line);
}
mbw.myClose();
}}

解决方案 »

  1.   

    后来我发现在在文本文件中,最后一行加上回车就没事了。因为在myReadLine()中末尾不加回车,就不会执行到两个if和一个return.所以改成这样就没事了。不过效率有所下降。
    public String myReadLine() throws IOException{
            StringBuilder sb = new StringBuilder();
            int ch = 0;
            while ((ch = myRead()) != -1) {
                if (ch == '\r')
                    continue;
                if (ch == '\n')
                    return sb.toString();
                sb.append((char) ch);
                if((ch = myRead()) == -1)//新加的判断
                   return sb.toString();
            }
            return null;
        }
        public void myClose() throws IOException {
            fr.close();
        }
      

  2.   

    import java.io.FileReader;
    import java.io.IOException;public class MyBufferedReader {
    private FileReader fr;
    private char[] buf = new char[1024];
    private int count = 0;
    private int pos = 0; public MyBufferedReader(FileReader f) {
    this.fr = f;
    } public int myRead() throws IOException {
    if (count == 0) {
    count = fr.read(buf);
    pos = 0;
    }
    if (count < 0)
    return -1;
    int ch = buf[pos++];
    count--;
    return ch;
    } public String myReadLine() throws IOException {
    StringBuilder sb = new StringBuilder();
    int ch = 0;
    while ((ch = myRead()) != -1) {
    if (ch == '\r')
    continue;
    if (ch == '\n')
    return sb.toString();
    sb.append((char) ch);
    if(count==0){
    return sb.toString();
    }

    }
    return null;
    } public void myClose() throws IOException {
    fr.close();
    }
    }红色部分是我加的,因为你最后一行没有返回sb.toString()就结束循环了