关于Bufferedreader的功能扩写

package cn.hncu.pattern.decorator.v1;

import java.io.FileReader;
import java.io.IOException;

public class MyBufferedReader {
private FileReader r;//封装或组合一个对象
private char[]cbuf = new char[1024];
private int count=0;//记录缓冲区中字符的个数 100
private int pos=0;
public MyBufferedReader(FileReader r){
this.r = r;
}

//功能增强1
public int myRead() throws IOException{
if(count<=0){
count = r.read(cbuf);//50
pos=0;
}
if(count==-1){
return -1;
}
count--;//每读一次,缓冲区中的还剩的字符数减1
char ch = cbuf[pos];//本次读的字符
pos++;
return ch;
}

public void close() throws IOException {
r.close();
}

//换行: linux-- window--
public String myReadLine() throws IOException{
StringBuffer sb = new StringBuffer();
int ch=0;
while( (ch=myRead())!=-1 ){
if(ch==' '){
continue;
}
if(ch==' '){
return sb.toString();
}
sb.append( (char)ch );//字符连接 str = str+(char)ch;
}
if(sb.length()!=0){//文件的最后一行是没有换行符的
return sb.toString();
}
return null;
}

}

-----------------------------------------------------------------

package cn.hncu.pattern.decorator.v1;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.junit.Test;

public class TestMyBufferedreader {

@Test
public void jdk_testRead() throws IOException {
FileReader r = new FileReader("a.txt");
BufferedReader br = new BufferedReader( r );
int ch=0;
while( (ch=br.read())!=-1 ){
System.out.print((char)ch);
}
br.close();
}
@Test
public void my_testRead() throws IOException {
FileReader r = new FileReader("a.txt");
MyBufferedReader br = new MyBufferedReader( r );
int ch=0;
while( (ch=br.myRead())!=-1 ){
System.out.print((char)ch);
}
br.close();
}


/////
@Test
public void jdk_testReadLine() throws IOException {
FileReader r = new FileReader("a.txt");
BufferedReader br = new BufferedReader( r );
String line = null;
while( (line =br.readLine())!=null ){
System.out.println(line);
}
br.close();
}

@Test
public void my_testReadLine() throws IOException {
FileReader r = new FileReader("a.txt");
MyBufferedReader br = new MyBufferedReader( r );
String line = null;
while( (line =br.myReadLine())!=null ){
System.out.println(line);
}
br.close();
}

}

原文地址:https://www.cnblogs.com/1314wamm/p/5701677.html