자바 학습 노트 의 Buffered Reader 와 Buffered Writer

25012 단어 Java
1.사용 이유
문자 흐름 읽 기와 쓰기 의 효율 을 높이 기 위해 버퍼 메커니즘 을 도입 하여 문자 대량 읽 기와 쓰 기 를 실시 하여 단일 문자 읽 기와 쓰기 의 효율 을 높 였 다.BufferedReader 는 문자 읽 기 속 도 를 빠르게 하 는 데 사용 되 며,BufferedWriter 는 쓰기 속 도 를 빠르게 하 는 데 사 용 됩 니 다.
2. BufferedWriter
2.1 계승 체계 와 방법
java.lang.Object 
    ----java.io.Writer 
    ------java.io.BufferedWriter 

구조 방법
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 

흔 한 방법
  • void close() Closes the stream, flushing it first.

  • void flush()Flushes the stream.//캐 시 영역 새로 고침
  • void newLine()라인 분리 기 를 작성 합 니 다.//줄 바 꿈 자 를 추가 합 니 다
  • void write(char[]cbuf,int off,int len)Writes a part 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 part of a String.//지정 한 문자열,off 오프셋,len 이 들 어 갈 문자열 의 길 이 를 기록 합 니 다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){ //    buff
                    bw.write(buff, 0, len);  //   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();
                    }
                }
            }
    
        }
    }
    

    3. BufferedReader
    3.2 계승 체계 와 방법
    1.상속 체계
     java.lang.Object 
         ----java.io.Reader 
            ----java.io.BufferedReader 
    

    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. 
    

    3.흔 한 방법
  • void close() Closes the stream and releases any system resources associated with it.
  • int read()단일 문 자 를 읽 습 니 다.//단일 문 자 를 읽 습 니 다
  • int read(char[]cbuf,int off,int len)Reads characters into a part of an array.//cbuf 를 읽 고 off 가 저장 하기 시작 하 는 오프셋,len 이 읽 는 길이
  • String readLine()텍스트 줄 을 읽 습 니 다.//줄 바 꿈 자 는 포함 되 지 않 습 니 다
  • 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.

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

    4 사용자 정의 Buffered Reader 와 Buffered Writer
    사용자 정의 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 == '
    '
    ){ ++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 == '
    '
    ){ ++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; } } }

    사용자 정의 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");
            }
        }
    
    }
    

    주:이상 은 간단 한 기능 실현 일 뿐 이 고 전면적으로 이해 하면 소스 코드 를 참고 할 수 있 습 니 다.

    좋은 웹페이지 즐겨찾기