BufferedReader&BufferedWriter

转载自:https://blog.csdn.net/qq_28261343/article/details/51900602

1. 使用缘由

为了提高字符流读写的效率,引入了缓冲机制,进行字符批量的读写,提高了单个字符读写的效率。BufferedReader用于加快读取字符的速度,BufferedWriter用于加快写入的速度

    
    
  • 1
  • 2

2. BufferedWriter

2.1 继承体系与方法

java.lang.Object 
    ----java.io.Writer 
    ------java.io.BufferedWriter 

    
    
  • 1
  • 2
  • 3
  • 4

构造方法

BufferedWriter(Writer out) 
    Creates a buffered character-output stream that uses a default-sized output buffer. 
BufferedWriter(Writer out,  int sz)//sz可以指定缓冲区的大小
    Creates a new buffered character-output stream that uses an output buffer of the given size 

    
    
  • 1
  • 2
  • 3
  • 4
  • 5

常见方法

void close() Closes the stream, flushing it first. 
void flush() Flushes the stream. //刷新缓存区
void newLine() Writes a line separator. //添加换行符
void write(char[] cbuf, int off, int len) Writes a portion of an array of characters. //写入指定的字符数组,off起始偏移量,len要写入的字符长度
void write(int c) Writes a single character. 
void write(String s, int off, int len) Writes a portion of a String. //写入指定的字符串,off偏移量,len要 入的字符串长度

    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2.2实例代码

package ReaderWriter;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/*
 * @author pecu
 *
 */
public class BufferedWriterReview {
    public static void main(String[] args) {
        //writeFile1();
        writeFile2();

    }

    private static void writeFile2() {
        BufferedWriter bw=null;
        BufferedReader br=null;
        try {
            br = new BufferedReader(new FileReader("fw.txt"));
            bw = new BufferedWriter(new FileWriter("bw2.txt"));
            String buff=null;
            while((buff=br.readLine())!=null){  //读取行,不包含换行符
                //将读取的行内容写入文件,偏移量为0,写入长度为buff的长度
                bw.write(buff, 0,buff.length());
                bw.newLine(); // 添加换行
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private static void writeFile1() {
        BufferedWriter bw=null;
        BufferedReader br=null;
        try {
            br = new BufferedReader(new FileReader("fw.txt"));
            bw = new BufferedWriter(new FileWriter("bw.txt"));
            char buff[] = new char[1024];
            int len;
            while((len=br.read(buff))!=-1){
                bw.write(buff, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bw!=null){
                try {
                    bw.close()`

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85

3. BufferedReader

3.2 继承体系与方法

1、继承体系

 java.lang.Object 
     ----java.io.Reader 
        ----java.io.BufferedReader 

    
    
  • 1
  • 2
  • 3
  • 4

2、构造方法

1、BufferedReader(Reader in) 
    Creates a buffering character-input stream that uses a default-sized input buffer. 
2、BufferedReader(Reader in, int sz)//sz可以指定缓冲区的大小
    Creates a buffering character-input stream that uses an input buffer of the specified size. 

    
    
  • 1
  • 2
  • 3
  • 4
  • 5

3、常见方法

void close() Closes the stream and releases any system resources associated with it.
int read() Reads a single character. //读取单个字符
int read(char[] cbuf, int off, int len) Reads characters into a portion of an array. //读取到cbuf,off开始存储的偏移量,len读取的长度
String readLine() Reads a line of text. //读取一行,不包含换行符
long skip(long n) Skips characters.//n为跳过的字符个数
boolean ready() Tells whether this stream is ready to be read. 
void reset() Resets the stream to the most recent mark. 

    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

3.2 实例代码

package ReaderWriter;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
 *
 * @author pecu
 *
 */
public class BufferedReaderReview {
    public static void main(String[] args) {
        readFile();
    }

    private static void readFile() {
        FileReader fr=null;
        BufferedReader br=null;
        try {
            fr=new FileReader("fw.txt");
            br = new BufferedReader(fr);
            String line=null;
            while((line=br.readLine())!=null){//不包含 line-termination characters
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

4 自定义BufferedReader与BufferedWriter

自定义BufferedReader

/**
 * 
 * @author pecu
 *
 */
public class CustomBufferedReader extends Reader{
    Reader r;
    private char[] buff; // 字符缓冲区
    private int lineNumber=0; // 行号
    public CustomBufferedReader(Reader r) {
        super();
        this.r = r;
        buff = new char[8192];
    }

    public int readInt() throws IOException{
        return r.read();
    }

    public String readLine2() throws IOException {
        int ch = 0;
        StringBuffer sb = new StringBuffer();
        synchronized (lock) {
            while((ch=readInt()) != -1){
                if(ch == '\r'){
                    continue;
                }
                if(ch == '\n'){
                    ++lineNumber;
                    return sb.toString();
                }
                sb.append((char)ch);
            }       
        }
        if(sb.length()==0) return null;
        ++lineNumber;
        return sb.toString();
    }

    public String readLine() throws IOException {
        int ch = 0;
        int count = 0;
        synchronized (lock) {
            while((ch=readInt()) != -1){  // 不到文件结尾
                if(ch == '\r'){  // '\r'不存
                    continue;
                }
                if(ch == '\n' ){
                    ++lineNumber;
                    return new String(buff,0,count);
                }

                buff[count++]= (char) ch;
            }
        }
        if(count==0) return null;  //如果读取为空
        ++lineNumber;
        return new String(buff,0,count);
    }

    public void close() throws IOException {
        if (r!=null) {
            r.close();
        }
    }

    public int getLineNumber() {
        return lineNumber;
    }

    @Override
    public int read(char[] cbuf, int off, int len) throws IOException {
        checkBounds(cbuf, off, len);
        return r.read(cbuf, off, len);
    }



    /**
     * 检查边界
     * 
     * @param cbuf
     * @param off
     * @param len
     */
    private void checkBounds(char[] cbuf, int off, int len) {
        if (cbuf == null) {
            throw new NullPointerException("cbuf is null");
        }

        if ((off < 0 || off > cbuf.length) || (len < 0 || len > cbuf.length)
                || (off + len) < 0 || (off + len) > cbuf.length) {
            throw new ArrayIndexOutOfBoundsException();
        }

        if (0==len) {
            return;
        }
    }
}

    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101

自定义BufferedWriter

/**
 * @author pecu
 */
public class CustomBufferedWriter extends Writer {
    private static final String LINE_SEPARATOR = System
            .getProperty("line.separator");
    private Writer writer;
    private static final int cacheSize = 8192; // 默认缓冲
    private char buff[]; // 缓冲区
    private int nChars, charIndex; // 

    public CustomBufferedWriter(Writer writer) {
        this(writer, cacheSize);
    }

    public CustomBufferedWriter(Writer writer, int sz) {
        super();
        if (sz <= 0) {
            throw new IllegalArgumentException("Buffered sz<=0");
        }
        this.writer = writer;
        nChars = sz;
        charIndex = 0;
        buff = new char[sz];
    }

    public void newLine() throws IOException {
        write(LINE_SEPARATOR);
        // write(LINE_SEPARATOR,0,LINE_SEPARATOR.length());
    }

    public void write(int c) throws IOException {
        if (charIndex >= nChars) {
            flushBuffer();
        }
        buff[charIndex++] = (char) c;
    }

    public void write(String str) throws IOException{
        write(str, 0, str.length());
    }

    @Override
    public void write(String str, int off, int len) throws IOException {
        securityCheck();
        // 1
//      char[] charArray = str.toCharArray();
//      write(charArray, off, len);

        // 2
        while (len>0) {
            int lenght=Math.min(nChars-charIndex, len);
            str.getChars(off, off+lenght, buff, charIndex);
            len-=lenght;
            charIndex+=lenght;
            if (charIndex>=nChars) {
                flushBuffer();
            }
        }
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        synchronized (lock) {
            checkBounds(cbuf, off, len);
            if (len>=nChars) {
                flushBuffer();
                writer.write(cbuf, 0, len);
                return;
            }

            while (len>0) {
                int length=Math.min(nChars-charIndex, len);
                System.arraycopy(cbuf, off, buff, charIndex, length);
                len-=length;
                charIndex+=length;
                if (charIndex>=nChars) {
                    flushBuffer();
                }
            }
        }
    }

    /**
     * 检查边界
     * 
     * @param cbuf
     * @param off
     * @param len
     */
    private void checkBounds(char[] cbuf, int off, int len) {
        if (cbuf == null) {
            throw new NullPointerException("cbuf is null");
        }

        if ((off < 0 || off > cbuf.length) || (len < 0 || len > cbuf.length)
                || (off + len) < 0 || (off + len) > cbuf.length) {
            throw new ArrayIndexOutOfBoundsException();
        }

        if (0==len) {
            return;
        }
    }

    @Override
    public void flush() throws IOException {
        synchronized (lock) {
            securityCheck();
            flushBuffer();
            writer.flush();
        }
    }

    @Override
    public void close() throws IOException {
        synchronized (lock) {
            securityCheck();
            flush();
            writer = null;
            buff = null;
        }
    }

    /**
     * 刷新到字符流
     * 
     * @throws IOException
     */
    public void flushBuffer() throws IOException {
        synchronized (lock) {
            securityCheck();
            if (charIndex == 0)
                return;
            writer.write(buff, 0, charIndex);
            charIndex = 0;
        }

    }

    /**
     * 检查流是否关闭
     * 
     * @throws IOException
     */
    public void securityCheck() throws IOException {
        if (writer == null) {
            throw new IOException("stream closed");
        }
    }

}

    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153

注:以上只是简单的功能实现,全面了解可参考源码。

1. 使用缘由

为了提高字符流读写的效率,引入了缓冲机制,进行字符批量的读写,提高了单个字符读写的效率。BufferedReader用于加快读取字符的速度,BufferedWriter用于加快写入的速度

  
  
  • 1
  • 2

2. BufferedWriter

2.1 继承体系与方法

java.lang.Object 
    ----java.io.Writer 
    ------java.io.BufferedWriter 

  
  
  • 1
  • 2
  • 3
  • 4

构造方法

BufferedWriter(Writer out) 
    Creates a buffered character-output stream that uses a default-sized output buffer. 
BufferedWriter(Writer out,  int sz)//sz可以指定缓冲区的大小
    Creates a new buffered character-output stream that uses an output buffer of the given size 

  
  
  • 1
  • 2
  • 3
  • 4
  • 5

常见方法

void close() Closes the stream, flushing it first. 
void flush() Flushes the stream. //刷新缓存区
void newLine() Writes a line separator. //添加换行符
void write(char[] cbuf, int off, int len) Writes a portion of an array of characters. //写入指定的字符数组,off起始偏移量,len要写入的字符长度
void write(int c) Writes a single character. 
void write(String s, int off, int len) Writes a portion of a String. //写入指定的字符串,off偏移量,len要 入的字符串长度

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2.2实例代码

package ReaderWriter;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/*
 * @author pecu
 *
 */
public class BufferedWriterReview {
    public static void main(String[] args) {
        //writeFile1();
        writeFile2();

    }

    private static void writeFile2() {
        BufferedWriter bw=null;
        BufferedReader br=null;
        try {
            br = new BufferedReader(new FileReader("fw.txt"));
            bw = new BufferedWriter(new FileWriter("bw2.txt"));
            String buff=null;
            while((buff=br.readLine())!=null){  //读取行,不包含换行符
                //将读取的行内容写入文件,偏移量为0,写入长度为buff的长度
                bw.write(buff, 0,buff.length());
                bw.newLine(); // 添加换行
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private static void writeFile1() {
        BufferedWriter bw=null;
        BufferedReader br=null;
        try {
            br = new BufferedReader(new FileReader("fw.txt"));
            bw = new BufferedWriter(new FileWriter("bw.txt"));
            char buff[] = new char[1024];
            int len;
            while((len=br.read(buff))!=-1){
                bw.write(buff, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bw!=null){
                try {
                    bw.close()`

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85

3. BufferedReader

3.2 继承体系与方法

1、继承体系

 java.lang.Object 
     ----java.io.Reader 
        ----java.io.BufferedReader 

  
  
  • 1
  • 2
  • 3
  • 4

2、构造方法

1、BufferedReader(Reader in) 
    Creates a buffering character-input stream that uses a default-sized input buffer. 
2、BufferedReader(Reader in, int sz)//sz可以指定缓冲区的大小
    Creates a buffering character-input stream that uses an input buffer of the specified size. 

  
  
  • 1
  • 2
  • 3
  • 4
  • 5

3、常见方法

void close() Closes the stream and releases any system resources associated with it.
int read() Reads a single character. //读取单个字符
int read(char[] cbuf, int off, int len) Reads characters into a portion of an array. //读取到cbuf,off开始存储的偏移量,len读取的长度
String readLine() Reads a line of text. //读取一行,不包含换行符
long skip(long n) Skips characters.//n为跳过的字符个数
boolean ready() Tells whether this stream is ready to be read. 
void reset() Resets the stream to the most recent mark. 

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

3.2 实例代码

package ReaderWriter;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
 *
 * @author pecu
 *
 */
public class BufferedReaderReview {
    public static void main(String[] args) {
        readFile();
    }

    private static void readFile() {
        FileReader fr=null;
        BufferedReader br=null;
        try {
            fr=new FileReader("fw.txt");
            br = new BufferedReader(fr);
            String line=null;
            while((line=br.readLine())!=null){//不包含 line-termination characters
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

4 自定义BufferedReader与BufferedWriter

自定义BufferedReader

/**
 * 
 * @author pecu
 *
 */
public class CustomBufferedReader extends Reader{
    Reader r;
    private char[] buff; // 字符缓冲区
    private int lineNumber=0; // 行号
    public CustomBufferedReader(Reader r) {
        super();
        this.r = r;
        buff = new char[8192];
    }

    public int readInt() throws IOException{
        return r.read();
    }

    public String readLine2() throws IOException {
        int ch = 0;
        StringBuffer sb = new StringBuffer();
        synchronized (lock) {
            while((ch=readInt()) != -1){
                if(ch == '\r'){
                    continue;
                }
                if(ch == '\n'){
                    ++lineNumber;
                    return sb.toString();
                }
                sb.append((char)ch);
            }       
        }
        if(sb.length()==0) return null;
        ++lineNumber;
        return sb.toString();
    }

    public String readLine() throws IOException {
        int ch = 0;
        int count = 0;
        synchronized (lock) {
            while((ch=readInt()) != -1){  // 不到文件结尾
                if(ch == '\r'){  // '\r'不存
                    continue;
                }
                if(ch == '\n' ){
                    ++lineNumber;
                    return new String(buff,0,count);
                }

                buff[count++]= (char) ch;
            }
        }
        if(count==0) return null;  //如果读取为空
        ++lineNumber;
        return new String(buff,0,count);
    }

    public void close() throws IOException {
        if (r!=null) {
            r.close();
        }
    }

    public int getLineNumber() {
        return lineNumber;
    }

    @Override
    public int read(char[] cbuf, int off, int len) throws IOException {
        checkBounds(cbuf, off, len);
        return r.read(cbuf, off, len);
    }



    /**
     * 检查边界
     * 
     * @param cbuf
     * @param off
     * @param len
     */
    private void checkBounds(char[] cbuf, int off, int len) {
        if (cbuf == null) {
            throw new NullPointerException("cbuf is null");
        }

        if ((off < 0 || off > cbuf.length) || (len < 0 || len > cbuf.length)
                || (off + len) < 0 || (off + len) > cbuf.length) {
            throw new ArrayIndexOutOfBoundsException();
        }

        if (0==len) {
            return;
        }
    }
}

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101

自定义BufferedWriter

/**
 * @author pecu
 */
public class CustomBufferedWriter extends Writer {
    private static final String LINE_SEPARATOR = System
            .getProperty("line.separator");
    private Writer writer;
    private static final int cacheSize = 8192; // 默认缓冲
    private char buff[]; // 缓冲区
    private int nChars, charIndex; // 

    public CustomBufferedWriter(Writer writer) {
        this(writer, cacheSize);
    }

    public CustomBufferedWriter(Writer writer, int sz) {
        super();
        if (sz <= 0) {
            throw new IllegalArgumentException("Buffered sz<=0");
        }
        this.writer = writer;
        nChars = sz;
        charIndex = 0;
        buff = new char[sz];
    }

    public void newLine() throws IOException {
        write(LINE_SEPARATOR);
        // write(LINE_SEPARATOR,0,LINE_SEPARATOR.length());
    }

    public void write(int c) throws IOException {
        if (charIndex >= nChars) {
            flushBuffer();
        }
        buff[charIndex++] = (char) c;
    }

    public void write(String str) throws IOException{
        write(str, 0, str.length());
    }

    @Override
    public void write(String str, int off, int len) throws IOException {
        securityCheck();
        // 1
//      char[] charArray = str.toCharArray();
//      write(charArray, off, len);

        // 2
        while (len>0) {
            int lenght=Math.min(nChars-charIndex, len);
            str.getChars(off, off+lenght, buff, charIndex);
            len-=lenght;
            charIndex+=lenght;
            if (charIndex>=nChars) {
                flushBuffer();
            }
        }
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        synchronized (lock) {
            checkBounds(cbuf, off, len);
            if (len>=nChars) {
                flushBuffer();
                writer.write(cbuf, 0, len);
                return;
            }

            while (len>0) {
                int length=Math.min(nChars-charIndex, len);
                System.arraycopy(cbuf, off, buff, charIndex, length);
                len-=length;
                charIndex+=length;
                if (charIndex>=nChars) {
                    flushBuffer();
                }
            }
        }
    }

    /**
     * 检查边界
     * 
     * @param cbuf
     * @param off
     * @param len
     */
    private void checkBounds(char[] cbuf, int off, int len) {
        if (cbuf == null) {
            throw new NullPointerException("cbuf is null");
        }

        if ((off < 0 || off > cbuf.length) || (len < 0 || len > cbuf.length)
                || (off + len) < 0 || (off + len) > cbuf.length) {
            throw new ArrayIndexOutOfBoundsException();
        }

        if (0==len) {
            return;
        }
    }

    @Override
    public void flush() throws IOException {
        synchronized (lock) {
            securityCheck();
            flushBuffer();
            writer.flush();
        }
    }

    @Override
    public void close() throws IOException {
        synchronized (lock) {
            securityCheck();
            flush();
            writer = null;
            buff = null;
        }
    }

    /**
     * 刷新到字符流
     * 
     * @throws IOException
     */
    public void flushBuffer() throws IOException {
        synchronized (lock) {
            securityCheck();
            if (charIndex == 0)
                return;
            writer.write(buff, 0, charIndex);
            charIndex = 0;
        }

    }

    /**
     * 检查流是否关闭
     * 
     * @throws IOException
     */
    public void securityCheck() throws IOException {
        if (writer == null) {
            throw new IOException("stream closed");
        }
    }

}

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153

注:以上只是简单的功能实现,全面了解可参考源码。

猜你喜欢

转载自blog.csdn.net/gaoyang8320/article/details/80110519