关于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--\n window--\r\n
public String myReadLine() throws IOException{
StringBuffer sb = new StringBuffer();
int ch=0;
while( (ch=myRead())!=-1 ){
if(ch=='\r'){
continue;
}
if(ch=='\n'){
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值