日期:2014-05-20  浏览次数:20842 次

今天刚学缓冲区,在自己编写MyBufferedReader 时,在使用myReadLine()时,总是不能督导最后一行,求大神们指点。
今天刚学缓冲区,在自己编写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();
}

}

------最佳解决方案--------------------
可以参考下flush()方法。
------其他解决方案--------------------
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();