Java bufferedwriter BufferedReader Source Analysis _java

Source: Internet
Author: User

One: BufferedWriter

1, the class function introduction:

BufferedWriter, cached character output stream, and his function is to provide caching for the incoming underlying character output stream, also when using the underlying character output to write characters or character arrays in the destination, each time the connection to the destination is opened once, so frequent access is efficient, It can also cause some damage to the storage media, for example, when we continue to write bytes to the disk, exaggerate a bit, a very large unit is the byte data to write to the disk of the specified file, did not write a byte to open a channel to this disk, this result is undoubtedly scary, And when we use BufferedWriter to wrap the underlying character output stream, such as FileReader, we can write the characters in the program to the file into the BufferedWriter's built-in cache space, and then, when a certain amount is reached, A one-time write to the FileReader stream, at this time, FileReader can open a channel, write this block of data to the file, although it is not possible to achieve a single access to all data to the effect of the disk, but also greatly improve the efficiency and reduce the amount of disk traffic! This is the meaning of his specific work here simply mention: Here may be said that the more chaotic, specific to see the source code, do not know how to look back here, when the program every time the character or character array written to the BufferedWriter, Checks to see if the cached character array in the BufferedWriter is BUF (the BUF size is the default or is specified when creating BW, generally using the default) is full, writes the character to the BUF if it is not full, and calls the underlying writer (char[] b if it is full. , int off, int len) writes all the characters in the BUF to the underlying out one at a time, if the character array is written, if the BUF is full with the upper full, if it can save the written character array, it is stored in the BUF, if it is not saved, and the number of characters to be written to buf is less than the length of buf, all characters in BUF are written to out and the characters to be written are stored in buf (stored from subscript 0), and if the characters to be written out exceed the length of the buf, write directly out,

2, BufferedWriter API Introduction:

    A: The key word
  private Writer out;		 Bottom character output stream

  
  private char cb[];		 Buffer array
  
  private int nchars, Nextchar;		 NCHARS--CB the SIZE,NEXTCHAR--CB of the next character is the subscript

  private static int defaultcharbuffersize = 8192;		 Default CB size

  private String lineseparator;		Line breaks, for newline methods. Different platforms have different values.

    B: Method

  of construction BufferedWriter (Writer out)		creates bufferedwriter BW using the default CB size.
  
  BufferedWriter (Writer out, int sz)		creates bufferedwriter BW using the default CB size.

    C: General method

  void Close ()		closes this stream, releasing resources related to this stream.
  
  void Flushbuffer ()		flushes the cached characters in CB flush to the underlying out,
  
  void flush ()	refreshes the stream, while refreshing the underlying out flow
  
  void newline ()		writes a newline character.
  
  void Write (int c)		writes a single character to the CB.
  
  void Write (char cbuf[], int off, int len)	writes a character from the subscript off length of Len to the CB
  
  void write (String s, int off, int len)		writes part of a string into CB

3. SOURCE Analysis

Package Com.chy.io.original.code;
Import java.io.IOException;


Import Java.io.PrintWriter; /** * provides buffering for character output streams and increases efficiency.
 You can use the specified character buffer array size, or you can use the default character buffer array size.

  * * public class BufferedWriter extends Writer {//bottom character output stream private Writer out;
  Buffer array private char cb[];

  NCHARS--CB the total number of characters, NEXTCHAR--CB the next character of the subscript private int nchars, Nextchar;

  Default CB size private static int defaultcharbuffersize = 8192; /** * Line separator string.
   This is the value of the line.separator * in the moment that's the stream was created. * line breaks, for newline methods.
   Different platforms have different values.

  * * Private String lineseparator;
   /** * Creates bufferedwriter BW using the default CB size.
  * * Public BufferedWriter (Writer out) {This (out, defaultcharbuffersize);
			/** * Use the specified CB size to create BR, Initialize related fields */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; Get under different platformsThe line break character representation. LineSeparator = (String) java.security.AccessController.doPrivileged (New Sun.security.action.GetPropertyAction (
  "Line.separator")); /** detects whether the underlying character output stream is closed/private void Ensureopen () throws IOException {if (out = = null) throw new IOException ("St
  Ream closed ");
   /** * The characters cached in CB flush to the underlying out, but not flush the underlying out.
   * and the CB will be emptied.
		  */void Flushbuffer () throws IOException {synchronized (lock) {ensureopen ();
		  if (Nextchar = = 0) return;
		  Out.write (CB, 0, Nextchar);
		Nextchar = 0;
   }/** * Writes a single character to the 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; }

  /**
   * Write a from subscript off length of Len characters into CB */public void write (char cbuf[], int off, int len) throws IOException {Synchroniz
	      Ed (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) {/* If Len is greater than CB length, the existing characters in CB and the characters in Cbuf are written to out, * instead of written to CB, and then written 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 (); /** * Writes part of a string into CB/public void write (string s, int off, int len) throws IOException {Synchron

	  Ized (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 ();
   /** * Writes a newline character.
  */public void newline () throws IOException {write (lineseparator);
		  /** * Refreshes this stream while refreshing the underlying out stream/public void flush () throws IOException {synchronized (lock) {flushbuffer ();
		Out.flush ();
   }/** * Closes this stream, releasing resources related to this stream.
		  */public void Close () throws IOException {synchronized (lock) {if (out = = null) {return;
		  try {flushbuffer ();
		    finally {out.close ();
		    out = null;
		  CB = NULL; }
		}
  }
}

4. Example Demo: A copy of a file that implements the character type is used in conjunction with the following BufferedReader.

Two: BufferedReader

1, the class function introduction:

The buffered character input stream, whose function is to provide buffering for the incoming underlying character input stream, reads through the characters in the underlying character input stream (in) into his own buffer (built-in cached character array), Then the program calls the BufferedReader read method reads the characters in the buffer into the program, and when the characters in the buffer are read, BufferedReader reads the next block of data from in to the buffer for the program to read, Until the data is read in, the benefit of this is to improve the efficiency of reading, the second is to reduce the number of connections to open storage media, detailed reasons below BufferedWriter said. The key method of filling is that every time the data in the buffer is read, the data is filled into the buffer from in, and the program reads the data from the memory 10 times times faster than it reads from the disk! This is a very frightening increase in efficiency, and we can't forbid it. Specifies the buffer size of the BufferedReader, after all, a long time to read in, and two of the relatively expensive memory prices, we can do is to find a reasonable point in it. Generally also do not need us to pay this heart, create BufferedReader use the default size of buffer.

2, BufferedReader API Introduction:

 A: The construction method

  BufferedReader (Reader in, int sz)		creates bufferedreader based on the specified size and the underlying character input stream. BR
  
  BufferedReader (Reader in)		buffer flow with the default size to create the underlying output stream
 

    B: General method

  void Close ()	closes this stream, releasing all resources
  
  related to this stream void mark (int readaheadlimit)	marks the position of this stream at this time
  
  boolean marksupported () to		determine whether this stream supports tag
  
  void reset ()	Reset in by last Mark's position
  
  Boolean ready ()		determines whether this stream can read the character
  
  int read ()		to read a single character and return as an integer. Returns-1 if the end of the read in is returned.
  
  int Read (char[] cbuf, int off, int len) reads the	len character in in to the Cbuf
  
  String readLine () read one line from the subscript off start length len
  
  long Skip (long N)		discards n characters in

3. SOURCE Analysis

Package Com.chy.io.original.code;

Import java.io.IOException; /** * Adds a character buffer CB array for the underlying character input stream. Increased efficiency * @version 1.1, 13/11/17 * @author andychen * * public class BufferedReader extends reader {private reader I 

  N
  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; /** * Creates bufferedreader based on the specified size and the underlying character input stream.
		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;
  /** * Use the default size to create a buffered stream of the underlying output stream */public BufferedReader (Reader in) {This (in, defaultcharbuffersize); /** detects that the underlying character input stream is turned off/private void Ensureopen () throws IOException {if (in = = null) throw new IOException ("
  Stream closed ");
   /** * Filled 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, Marke
			  Dchar, 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; }/** * Reads a single character and returns as an integer.
   Returns-1 if the end of the read in is returned.
		  */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++]; /** * will read in Len characters to cbuf from subscript off start length len */private int read1 (char[] cbuf, int off, int len) throws Ioex ception {if (Nextchar >= nchars) {/* If the requested length is at least as large as the buffer, and if t Here are no mark/reset activity, and if line feeds are does not being skipped, don't bother to copy the characters into T
		He    Local buffer. In this way buffered streams is 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;
    /** * reads in Len characters to cbuf from subscript off start length 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; 
		}/** * Reads a row from in, ignores the newline character */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);
  /** * Reads a row from in, */public String ReadLine () throws IOException {return ReadLine (false); /** * Discard in n characters/public long skip (long N) throws IOException {if (n < 0L) {throw new Illegalargu
		Mentexception ("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;
   }/** * Determines whether the CB is empty, or whether there are readable characters in the bottom in.
	
		  */public Boolean Ready () throws IOException {synchronized (lock) {ensureopen (); * * If newline needs to being skipped and the next char to being read * * is a newline character, then just skip it ri
		   Ght away. */if (SKIPLF) {/* Note that In.ready () would return true if and only if the next * read on the stream would no
			 T block.
			*/if (Nextchar >= nchars && in.ready ()) {fill ();
			  } if (Nextchar < nchars) {if (Cb[nextchar] = = ' \ n ') nextchar++;
			SKIPLF = false; } return (Nextchar < nchars) | |
		In.ready ();
  }/** * Determines whether this stream supports tags/public boolean marksupported () {return true;
   /** * marks the location of this stream at this time and allows up to readaheadlimit characters to be read before the reset method is invalidated. */
  public void mark (int readaheadlimit) throws IOException {if (Readaheadlimit < 0) {throw new Illegalargumente
		Xception ("Read-ahead limit < 0");
		  } synchronized (lock) {ensureopen ();
		  This.readaheadlimit = Readaheadlimit;
		  Markedchar = Nextchar;
		MARKEDSKIPLF = SKIPLF; }/** * Resets the position of Mark in the last time.
   The next character is read from the last mark's position.
		  */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; }//Close this stream, release all resources related to this stream public void close () throws IOException {synchronized (lock) {if (in = = NULL) ret
		  Urn
		  In.close ();
		  in = null;
		CB = NULL; }
  }
}

4, Example Demo:

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 {
	/**
	 * Here's a simple test for these two classes, which is to wrap the character stream of the file and implement a copy of the file
	 * Interested can test the efficiency, steal a lazy, can be ignored/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);
		}
		Do not forget to refresh and close the flow, otherwise, on the one hand, the resources are not released in time, on the other hand may be lost
		br.close ();
		Bw.flush ();
		Bw.close ();
	}

Summarize:

        for BufferedReader, BufferedWriter, Essence is to add buffering function for the underlying character input output stream, First of all the data to read or write in the underlying stream, read or write to buffer, and then operate on the buffer, so as not only efficient, but also save resources. Finally, in the program, for efficiency considerations, should also be used for low-level flow of these two classes for decoration, rather than directly with the flow directly, feel that can be achieved on the line.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.