码迷,mamicode.com
首页 > 其他好文 > 详细

关于Bufferedreader的功能扩写

时间:2016-07-24 22:25:41      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

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();
}

}

关于Bufferedreader的功能扩写

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!