程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java BufferedWriter BufferedReader 源碼剖析

Java BufferedWriter BufferedReader 源碼剖析

編輯:關於JAVA

Java BufferedWriter BufferedReader 源碼剖析。本站提示廣大學習愛好者:(Java BufferedWriter BufferedReader 源碼剖析)文章只能為提供參考,不一定能成為您想要的結果。以下是Java BufferedWriter BufferedReader 源碼剖析正文


一:BufferedWriter

 1、類功效簡介:

        BufferedWriter、緩存字符輸入流、他的功效是為傳入的底層字符輸入流供給緩存功效、異樣當應用底層字符輸入流向目標地中寫入字符或許字符數組時、每寫入一次就要翻開一次到目標地的銜接、如許頻仍的拜訪赓續效力底下、也有能夠會對存儲介質形成必定的損壞、好比當我們向磁盤中赓續的寫入字節時、誇大一點、將一個異常年夜單元是G的字節數據寫入到磁盤的指定文件中的、沒寫入一個字節就要翻開一次到這個磁盤的通道、這個成果無疑是恐懼的、而當我們應用BufferedWriter將底層字符輸入流、好比FileReader包裝一下以後、我們可以在法式中先將要寫入到文件中的字符寫入到BufferedWriter的內置緩存空間中、然後當到達必定數目時、一次性寫入FileReader流中、此時、FileReader便可以翻開一次通道、將這個數據塊寫入到文件中、如許做固然弗成能到達一次拜訪就將一切數據寫入磁盤中的後果、但也年夜年夜進步了效力和削減了磁盤的拜訪量!這就是其意義地點、 他的詳細任務道理在這裡簡略提一下:這裡能夠說的比擬亂、詳細可以看源碼、不懂再回頭看看這裡、當法式中每次將字符或許字符數組寫入到BufferedWriter中時、都邑檢討BufferedWriter中的緩存字符數組buf(buf的年夜小是默許的或許在創立bw時指定的、普通應用默許的就好)能否存滿、假如沒有存滿則將字符寫入到buf中、假如存滿、則挪用底層的writer(char[] b, int off, int len)將buf中的一切字符一次性寫入究竟層out中、假如寫入的是字符數組、假如buf中已滿則同下面滿的時刻的處置、假如可以或許存下寫入的字符數組、則存入buf中、假如存不下、而且要寫入buf的字符個數小於buf的長度、則將buf中一切字符寫入到out中、然後將要寫入的字符寄存到buf中(從下標0開端寄存)、假如要寫入out中的字符跨越buf的長度、則直接寫入out中、

2、BufferedWriter  API簡介:

    A:症結字
  private Writer out;		 底層字符輸入流

  
  private char cb[];		 緩沖數組
  
  private int nChars, nextChar;		 nChars--cb的size,nextChar--cb中下一個字符的下標

  private static int defaultCharBufferSize = 8192;		 默許cb年夜小

  private String lineSeparator;		換行符、用於newLine辦法。分歧平台具有分歧的值。

    B:結構辦法

  BufferedWriter(Writer out)		應用默許cb年夜小創立BufferedWriter bw。
  
  BufferedWriter(Writer out, int sz)		應用默許cb年夜小創立BufferedWriter bw。

    C:普通辦法

  void close()		封閉此流、釋放與此流有關的資本。
  
  void flushBuffer()		將cb中緩存的字符flush究竟層out中、
  
  void flush()	刷新此流、同時刷新底層out流
  
  void newLine()		寫入一個換行符。
  
  void write(int c)		將一個單個字符寫入到cb中。
  
  void write(char cbuf[], int off, int len)	將一個從下標off開端長度為len個字符寫入cb中
  
  void write(String s, int off, int len)		將一個字符串的一部門寫入cb中

3、源碼剖析

package com.chy.io.original.code;

import java.io.IOException;
import java.io.PrintWriter;


/**
 * 為字符輸入流供給緩沖功效、進步效力。可使用指定字符緩沖數組年夜小也能夠應用默許字符緩沖數組年夜小。
 */

public class BufferedWriter extends Writer {

	//底層字符輸入流
  private Writer out;

  //緩沖數組
  private char cb[];
  //nChars--cb中總的字符數,nextChar--cb中下一個字符的下標
  private int nChars, nextChar;

  //默許cb年夜小
  private static int defaultCharBufferSize = 8192;

  /**
   * Line separator string. This is the value of the line.separator
   * property at the moment that the stream was created.
   * 換行符、用於newLine辦法。分歧平台具有分歧的值。
   */
  private String lineSeparator;

  /**
   * 應用默許cb年夜小創立BufferedWriter bw。
   */
  public BufferedWriter(Writer out) {
  	this(out, defaultCharBufferSize);
  }

  /**
   * 應用指定cb年夜小創立br、初始化相干字段
   */
  public BufferedWriter(Writer out, int sz) {
		super(out);
			if (sz <= 0)
			  throw new IllegalArgumentException("Buffer size <= 0");
			this.out = out;
			cb = new char[sz];
			nChars = sz;
			nextChar = 0;
			//獲得分歧平台下的換行符表現方法。
			lineSeparator =	(String) java.security.AccessController.doPrivileged(
		        new sun.security.action.GetPropertyAction("line.separator"));
  }

  /** 檢測底層字符輸入流能否封閉*/
  private void ensureOpen() throws IOException {
		if (out == null)
		  throw new IOException("Stream closed");
  }

  /**
   * 將cb中緩存的字符flush究竟層out中、然則不flush底層out中的字符。
   * 而且將cb清空。
   */
  void flushBuffer() throws IOException {
		synchronized (lock) {
		  ensureOpen();
		  if (nextChar == 0)
		  	return;
		  out.write(cb, 0, nextChar);
		  nextChar = 0;
		}
  }

  /**
   * 將一個單個字符寫入到cb中。
   */
  public void write(int c) throws IOException {
		synchronized (lock) {
		  ensureOpen();
		  if (nextChar >= nChars)
			flushBuffer();
		  cb[nextChar++] = (char) c;
		}
  }

  /**
   * Our own little min method, to avoid loading java.lang.Math if we've run
   * out of file descriptors and we're trying to print a stack trace.
   */
  private int min(int a, int b) {
	if (a < b) return a;
	return b;
  }

  /**
   * 將一個從下標off開端長度為len個字符寫入cb中
   */
  public void write(char cbuf[], int off, int len) throws IOException {
		synchronized (lock) {
		  ensureOpen();
	      if ((off < 0) || (off > cbuf.length) || (len < 0) ||
	        ((off + len) > cbuf.length) || ((off + len) < 0)) {
	        throw new IndexOutOfBoundsException();
	      } else if (len == 0) {
	        return;
	      } 
	
		  if (len >= nChars) {
				/* 假如len年夜於cb的長度、那末就直接將cb中現有的字符和cbuf中的字符寫入out中、
				 * 而不是寫入cb、再寫入out中 。
				 */
				flushBuffer();
				out.write(cbuf, off, len);
				return;
		  }
	
		  int b = off, t = off + len;
		  while (b < t) {
				int d = min(nChars - nextChar, t - b);
				System.arraycopy(cbuf, b, cb, nextChar, d);
				b += d;
				nextChar += d;
				if (nextChar >= nChars)
				  flushBuffer();
		  }
		}
  }

  /**
   * 將一個字符串的一部門寫入cb中
   */
  public void write(String s, int off, int len) throws IOException {
	synchronized (lock) {
	  ensureOpen();

	  int b = off, t = off + len;
	  while (b < t) {
		int d = min(nChars - nextChar, t - b);
		s.getChars(b, b + d, cb, nextChar);
		b += d;
		nextChar += d;
		if (nextChar >= nChars)
		  flushBuffer();
	  }
	}
  }

  /**
   * 寫入一個換行符。
   */
  public void newLine() throws IOException {
  	write(lineSeparator);
  }

  /**
   * 刷新此流、同時刷新底層out流
   */
  public void flush() throws IOException {
		synchronized (lock) {
		  flushBuffer();
		  out.flush();
		}
  }
  /**
   * 封閉此流、釋放與此流有關的資本。
   */
  public void close() throws IOException {
		synchronized (lock) {
		  if (out == null) {
			return;
		  }
		  try {
		    flushBuffer();
		  } finally {
		    out.close();
		    out = null;
		    cb = null;
		  }
		}
  }
}

 4、實例演示:與上面的BufferedReader聯合應用完成字符類型的文件的拷貝。

二:BufferedReader

 1、類功效簡介:

        緩沖字符輸出流、他的功效是為傳入的底層字符輸出流供給緩沖功效、他會經由過程底層字符輸出流(in)中的字符讀取到本身的buffer中(內置緩存字符數組)、然後法式挪用BufferedReader的read辦法將buffer中的字符讀取到法式中、當buffer中的字符被讀取完以後、BufferedReader會從in中讀取下一個數據塊到buffer中供法式讀取、直到in中數據被讀取終了、如許做的利益一是進步了讀取的效力、二是削減了翻開存儲介質的銜接次數、具體的緣由上面BufferedWriter有說到。其有個症結的辦法fill()就是每當buffer中數據被讀取完以後從in中將數據填充到buffer中、法式從內存中讀取數據的速度是從磁盤中讀取的十倍!這是一個很恐懼的效力的晉升、同時我們也不克不及無制止的指定BufferedReader的buffer年夜小、究竟、一次性讀取in中耗時較長、二是內存價錢絕對昂貴、我們能做的就是盡可能在個中找到公道點。普通也不消我們費這個心、創立BufferedReader時應用buffer的默許年夜小就好。

2、BufferedReader  API簡介:

 A:結構辦法

  BufferedReader(Reader in, int sz)		依據指定年夜小和底層字符輸出流創立BufferedReader。br
  
  BufferedReader(Reader in)		應用默許年夜小創立底層輸入流的緩沖流
 

    B:普通辦法

  void close()	封閉此流、釋放與此流有關的一切資本
  
  void mark(int readAheadLimit)	標志此流此時的地位
  
  boolean markSupported()		斷定此流能否支撐標志
  
  void reset()	重置in被最初一次mark的地位
  
  boolean ready()		斷定此流能否可以讀取字符
  
  int read()		讀取單個字符、以整數情勢前往。假如讀到in的開頭則前往-1。
  
  int read(char[] cbuf, int off, int len)	將in中len個字符讀取到cbuf從下標off開端長度len中
  
  String readLine()	讀取一行
  
  long skip(long n)		拋棄in中n個字符

 3、源碼剖析

package com.chy.io.original.code;

import java.io.IOException;

/**
 * 為底層字符輸出流添加字符緩沖cb數組。進步效力
 * @version 	1.1, 13/11/17
 * @author		andyChen
 */

public class BufferedReader extends Reader {

  private Reader in; 

  private char cb[];
  private int nChars, nextChar;

  private static final int INVALIDATED = -2;
  private static final int UNMARKED = -1;
  private int markedChar = UNMARKED;
  private int readAheadLimit = 0; /* Valid only when markedChar > 0 */

  /** If the next character is a line feed, skip it */
  private boolean skipLF = false;

  /** The skipLF flag when the mark was set */
  private boolean markedSkipLF = false;

  private static int defaultCharBufferSize = 8192;
  private static int defaultExpectedLineLength = 80;

  /**
   * 依據指定年夜小和底層字符輸出流創立BufferedReader。br
   */
  public BufferedReader(Reader in, int sz) {
		super(in);
		if (sz <= 0)
		  throw new IllegalArgumentException("Buffer size <= 0");
		this.in = in;
		cb = new char[sz];
		nextChar = nChars = 0;
  }

  /**
   * 應用默許年夜小創立底層輸入流的緩沖流
   */
  public BufferedReader(Reader in) {
  	this(in, defaultCharBufferSize);
  }

  /** 檢測底層字符輸出流in能否封閉 */
  private void ensureOpen() throws IOException {
		if (in == null)
		  throw new IOException("Stream closed");
  }

  /**
   * 填充cb。
   */
  private void fill() throws IOException {
		int dst;
		if (markedChar <= UNMARKED) {
		  /* No mark */
		  dst = 0;
		} else {
		  /* Marked */
		  int delta = nextChar - markedChar;
		  if (delta >= readAheadLimit) {
			/* Gone past read-ahead limit: Invalidate mark */
			markedChar = INVALIDATED;
			readAheadLimit = 0;
			dst = 0;
		  } else {
			if (readAheadLimit <= cb.length) {
			  /* Shuffle in the current buffer */
			  System.arraycopy(cb, markedChar, cb, 0, delta);
			  markedChar = 0;
			  dst = delta;
			} else {
			  /* Reallocate buffer to accommodate read-ahead limit */
			  char ncb[] = new char[readAheadLimit];
			  System.arraycopy(cb, markedChar, ncb, 0, delta);
			  cb = ncb;
			  markedChar = 0;
			  dst = delta;
			}
	        nextChar = nChars = delta;
		  }
		}
	
		int n;
		do {
		  n = in.read(cb, dst, cb.length - dst);
		} while (n == 0);
		if (n > 0) {
		  nChars = dst + n;
		  nextChar = dst;
		}
  }

  /**
   * 讀取單個字符、以整數情勢前往。假如讀到in的開頭則前往-1。
   */
  public int read() throws IOException {
		synchronized (lock) {
		  ensureOpen();
		  for (;;) {
			if (nextChar >= nChars) {
			  fill();
			  if (nextChar >= nChars)
				return -1;
			}
			if (skipLF) {
			  skipLF = false;
			  if (cb[nextChar] == '\n') {
				nextChar++;
				continue;
			  }
			}
			return cb[nextChar++];
		  }
		}
  }

  /**
   * 將in中len個字符讀取到cbuf從下標off開端長度len中
   */
  private int read1(char[] cbuf, int off, int len) throws IOException {
		if (nextChar >= nChars) {
		  /* If the requested length is at least as large as the buffer, and
		    if there is no mark/reset activity, and if line feeds are not
		    being skipped, do not bother to copy the characters into the
		    local buffer. In this way buffered streams will cascade
		    harmlessly. */
		  if (len >= cb.length && markedChar <= UNMARKED && !skipLF) {
			return in.read(cbuf, off, len);
		  }
		  fill();
		}
		if (nextChar >= nChars) return -1;
		if (skipLF) {
		  skipLF = false;
		  if (cb[nextChar] == '\n') {
			nextChar++;
			if (nextChar >= nChars)
			  fill();
			if (nextChar >= nChars)
			  return -1;
		  }
		}
		int n = Math.min(len, nChars - nextChar);
		System.arraycopy(cb, nextChar, cbuf, off, n);
		nextChar += n;
		return n;
  }

  /**
   * 將in中len個字符讀取到cbuf從下標off開端長度len中
   */
  public int read(char cbuf[], int off, int len) throws IOException {
    synchronized (lock) {
	  ensureOpen();
      if ((off < 0) || (off > cbuf.length) || (len < 0) ||
        ((off + len) > cbuf.length) || ((off + len) < 0)) {
        throw new IndexOutOfBoundsException();
      } else if (len == 0) {
        return 0;
      }

	  int n = read1(cbuf, off, len);
	  if (n <= 0) return n;
	  while ((n < len) && in.ready()) {
		int n1 = read1(cbuf, off + n, len - n);
		if (n1 <= 0) break;
		n += n1;
	  }
	  return n;
	}
  }

  /**
   * 從in中讀取一行、能否疏忽換行符
   */
  String readLine(boolean ignoreLF) throws IOException {
		StringBuffer s = null;
		int startChar;
	
    synchronized (lock) {
      ensureOpen();
	  boolean omitLF = ignoreLF || skipLF;
		bufferLoop:
		for (;;) {
	
			if (nextChar >= nChars)
			  fill();
			if (nextChar >= nChars) { /* EOF */
			  if (s != null && s.length() > 0)
				return s.toString();
			  else
				return null;
			}
			boolean eol = false;
			char c = 0;
			int i;
	
	        /* Skip a leftover '\n', if necessary */
			if (omitLF && (cb[nextChar] == '\n')) 
	          nextChar++;
			skipLF = false;
			omitLF = false;
	
		  charLoop:
			for (i = nextChar; i < nChars; i++) {
			  c = cb[i];
			  if ((c == '\n') || (c == '\r')) {
				eol = true;
				break charLoop;
			  }
			}
	
			startChar = nextChar;
			nextChar = i;
	
			if (eol) {
			  String str;
			  if (s == null) {
				str = new String(cb, startChar, i - startChar);
			  } else {
				s.append(cb, startChar, i - startChar);
				str = s.toString();
			  }
			  nextChar++;
			  if (c == '\r') {
				skipLF = true;
			  }
			  return str;
			}
			
			if (s == null) 
			  s = new StringBuffer(defaultExpectedLineLength);
			s.append(cb, startChar, i - startChar);
		  }
    }
  }

  /**
   * 從in中讀取一行、
   */
  public String readLine() throws IOException {
    return readLine(false);
  }

  /**
   * 拋棄in中n個字符
   */
  public long skip(long n) throws IOException {
		if (n < 0L) {
		  throw new IllegalArgumentException("skip value is negative");
		}
		synchronized (lock) {
		  ensureOpen();
		  long r = n;
		  while (r > 0) {
			if (nextChar >= nChars)
			  fill();
			if (nextChar >= nChars)	/* EOF */
			  break;
			if (skipLF) {
			  skipLF = false;
			  if (cb[nextChar] == '\n') {
				nextChar++;
			  }
			}
			long d = nChars - nextChar;
			if (r <= d) {
			  nextChar += r;
			  r = 0;
			  break;
			}
			else {
			  r -= d;
			  nextChar = nChars;
			}
		  }
		  return n - r;
		}
  }

  /**
   * 斷定cb中能否為空、或許底層in中能否有可讀字符。
   */
  public boolean ready() throws IOException {
		synchronized (lock) {
		  ensureOpen();
	
		  /* 
		   * If newline needs to be skipped and the next char to be read
		   * is a newline character, then just skip it right away.
		   */
		  if (skipLF) {
			/* Note that in.ready() will return true if and only if the next 
			 * read on the stream will not block.
			 */
			if (nextChar >= nChars && in.ready()) {
			  fill();
			}
			if (nextChar < nChars) {
			  if (cb[nextChar] == '\n') 
				nextChar++;
			  skipLF = false;
			} 
		  }
		  return (nextChar < nChars) || in.ready();
		}
  }

  /**
   * 斷定此流能否支撐標志
   */
  public boolean markSupported() {
  	return true;
  }

  /**
   * 標志此流此時的地位、當挪用reset辦法掉效前最多許可讀取readAheadLimit個字符。
   */
  public void mark(int readAheadLimit) throws IOException {
		if (readAheadLimit < 0) {
		  throw new IllegalArgumentException("Read-ahead limit < 0");
		}
		synchronized (lock) {
		  ensureOpen();
		  this.readAheadLimit = readAheadLimit;
		  markedChar = nextChar;
		  markedSkipLF = skipLF;
		}
  }

  /**
   * 重置in被最初一次mark的地位。即下一個字符從被最初一次mark的地位開端讀取。
   */
  public void reset() throws IOException {
		synchronized (lock) {
		  ensureOpen();
		  if (markedChar < 0)
			throw new IOException((markedChar == INVALIDATED)
					   ? "Mark invalid"
					   : "Stream not marked");
		  nextChar = markedChar;
		  skipLF = markedSkipLF;
		}
  }

  //封閉此流、釋放與此流有關的一切資本
  public void close() throws IOException {
		synchronized (lock) {
		  if (in == null)
			return;
		  in.close();
		  in = null;
		  cb = null;
		}
  }
}

4、實例演示:

package com.chy.io.original.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterAndBufferedReaderTest {
	/**
	 * 這裡對這兩個類的測試比擬簡略、就是對文件字符流停止包裝、完成文件拷貝
	 * 有興致的可以測試一下效力、、偷個懶、、可疏忽
	 */
	public static void main(String[] args) throws IOException{
		File resouceFile = new File("D:\\test.txt");
		File targetFile = new File("E:\\copyOftest.txt");
		
		BufferedReader br = new BufferedReader(new FileReader(resouceFile));
		BufferedWriter bw = new BufferedWriter(new FileWriter(targetFile));
		
		char[] cbuf = new char[1024];
		int n = 0;
		while((n = br.read(cbuf)) != -1){
			bw.write(cbuf, 0, n);
		}
		//不要忘卻刷新和封閉流、不然一方面資本沒有實時釋放、另外一方面有能夠照成數據喪失
		br.close();
		bw.flush();
		bw.close();
	}
}

總結:

        關於BufferedReader、BufferedWriter、實質就是為底層字符輸出輸入流添加緩沖功效、先將底層流中的要讀取或許要寫入的數據先以一次讀取一組的情勢來說數據讀取或許寫入到buffer中、再對buffer停止操作、如許不只效力、還能節儉資本。最初、在法式中、出於效力的斟酌、也應為初級流應用這兩個類停止裝潢一下、而不是直接拿著流直接上、認為能完成就行。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved