Java IO6: Character Stream advanced and BufferedWriter, BufferedReader

Source: Internet
Author: User

Original: http://www.cnblogs.com/xrq730/p/4890052.html

The difference between a character stream and a byte stream

 Public Static voidMain (string[] args)throwsexception{File File=NewFile ("D:/writer.txt"); Writer out=NewFileWriter (file); //declares a String type objectString str = "Hello World!!!";    Out.write (str);            Out.close (); //Read File OperationReader in =Newfilereader (file); //open up a space to receive the data that the file reads in    CharC0[] =New Char[1024]; inti = 0; //Pass the C0 reference to the Read () method, and this method returns the number of read-in datai =In.read (C0);            In.close (); if(-1 = =i) {System.out.println ("No data in file"); }    Else{System.out.println (NewString (C0, 0, i)); }}

Line 8th "Out.close ()" Comment off can look at the effect, "writer.txt" must be empty, the console output is "File no data", explain why.

Character stream and byte stream are very similar, but there are differences, from the Internet to find a picture:

From the figure, the biggest difference between the character stream and the byte stream is that the byte stream does not use the buffer (memory) itself, the file itself is directly manipulated, and the character stream operation uses the buffer to manipulate the file through the buffer. This also explains the problem with the program above, why it is not possible to write to the file because the resource is not close (). Because the contents of the buffer are forced to be output when the character stream is closed, the contents of the buffer cannot be output if it is not closed .

What is a buffer? Simply understood, a buffer is a special area of memory. Why use buffers? Because if a program frequently operates on a resource (file or database), performance can be very low, in order to improve performance, you can temporarily read some of the data into the memory of a piece of the area, and then directly from the region to read the data, because the speed of reading memory faster than the speed of reading the file content on disk.

In a character stream operation, all characters are formed in memory, and all of the content is temporarily stored in memory before output, so buffers are used.

If you do not want to output the contents of the character stream when you close it, use the writer's Flush () method.

The principle of character stream

Java supports character stream and byte stream, the character stream itself is a special kind of byte stream, the reason is to have a character stream, because there are a lot of characters in Java operation, so there is a character stream. The conversion of byte stream and character stream is in the medium of InputStreamReader and OutputStreamWriter, InputStreamReader can decode the bytes in a stream into characters, OutputStreamWriter can encode written characters into a byte stream from the post-section.

Decoding bytes in InputStreamReader is done by Streamdecoder, Streamdecoder is the implementation class of reader, defined at the beginning of InputStreamReader:

Extends Reader {    final streamdecoder SD; 

Similarly, the encoded bytes in the Outputstreadwriter are done by Streamencoder, Streamencoder is the writer's implementation class, defined at the beginning of the OutputStreamWriter:

Extends Writer {    final Streamencoder se;

If you do not specify the CharSet encoding format for Streamdecoder and Streamencoder, the default character set in the local environment will be used, such as GBK encoding is used in the Chinese environment.

The InputStreamReader has two main constructors:

1, InputStreamReader (InputStream in)

2, InputStreamReader (InputStream in, String CharsetName)

OutputStreamWriter also has two main constructors:

1, OutputStreamWriter (OutputStream out)

2, OutputStreamWriter (OutputStream out, String charsetname)

From the constructor, we can see that the character stream is realized by using the byte stream. The difference between the two constructors of InputStreamReader and OutputStreamWriter is that one is the default character set used, and one can specify the character set name. In fact, FileReader and FileWriter can look at the source code, very simple, only the constructor, the inside are based on the absolute path of the files passed in or the incoming file instance, new out of FileInputStream and FileOutputStream, The constructor method for calling InputStreamReader and OutputStreamWriter. Doing so helps developers save the process of instantiating FileInputStream and FileOutputStream, allowing developers to directly use filename or file as a constructor parameter .

BufferedWriter, BufferedReader

In order to achieve maximum efficiency and avoid frequent conversion between characters and bytes, it is best not to read and write directly using the two classes of FileReader and FileWriter, and use the BufferedWriter wrapper outputstreamwriter, Use BufferedReader to wrap the inputstreamreader. Similarly, there is no "buffered" file under the D drive, and the code example is:

 Public Static voidMain (string[] args)throwsexception{File File=NewFile ("D:/buffered.txt"); Writer writer=NewFileWriter (file); BufferedWriter BW=NewBufferedWriter (writer); Bw.write ("1234\n"); Bw.write ("2345\n"); Bw.write ("3456\n"); Bw.write ("\ n"); Bw.write ("4567\n");    Bw.close ();            Writer.close (); if(File.exists () && file.getname (). EndsWith (". txt") {Reader Reader=Newfilereader (file); BufferedReader BR=NewBufferedReader (reader); String Str=NULL;  while(str = br.readline ())! =NULL) {System.out.println (str);        } reader.close ();    Br.close (); }    }

Run, first of all the "Buffered.txt" in the D-disk, the file content is:

Then take a look at the console output:

1234234534564567

No problem, output the contents of the file. Note two points:

1, write with BufferedWriter, write content will be placed in the buffer, until you encounter close (), flush () the content will be written to the file once. Also note the order of close (), must first close the BufferedWriter, and then close writer, can not be reversed, because the BufferedWriter write operation is written by the writer method, if you close the writer, you can not Writes the data in the buffer to the file, throws an exception

2, use BufferedReader to read operation, can not use the parent reader to point to it, because ReadLine () This method is BufferedReader unique, the role of ReadLine () is to read the contents of the file row by line

Java IO6: Character Stream advanced and BufferedWriter, BufferedReader

Related Article

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.