J2SE Knowledge points inductive note (vii)---Java IO Part 4: Basic character stream

Source: Internet
Author: User
Tags file copy

J2SE Knowledge points inductive note (vii)---Java IO Part 4: Basic character stream

--Reprint Please specify Source: Coder-pig


Introduction to this section:


In the previous section, we learned about some basic byte streams in the Java IO Stream, both of which are inputstream and

A subclass of OutputStream; This section learns the character stream is the subclass of reader and writer, well, say not much,

Start the content of this section!



The text of this section:

1.Reader class and writer class related methods:

ps:~ Piglet is lazy, so do not knock method and parse, direct cut API Diagram bar, you can flip through the API documentation:



related methods of the ①reader class:




related methods of the ②writer class:





something to figure out:

1) The difference between a binary file and a text file:

A: If a file is dedicated to storing text characters and does not contain characters other than text,

It can be called a text file. In addition to the file is a binary file!

2) The difference between Inputstream,outputstream and Reader,writer:

A: The former is to deal with Byte stream, the latter is to deal with character stream;

The former is mainly used to manipulate the contents of binary data, while the latter is used to manipulate the content of text data;

The former operates directly on a byte array, which is also decode and encode~ when operated.






2.FileReader and the use of the FileWriter class:

Construction Method:





code example:

The code shown here reads the contents of the file and completes a simple copy of the file.

Then write the code, we write the time remember to carry out abnormal capture oh ~


① writes data to the file, reads the data display:

FileWriter FileWriter = new FileWriter ("D:/one.txt"); Filewriter.write ("I am the coder-pig~ of Moe"); Filewriter.close ();// Read the contents of the file: FileReader filereader = new  FileReader ("D:/one.txt");//user-buffered character array char[] Cbuf = new Char[1024];int len = Filereader.read (CBUF); System.out.println (New String (Cbuf,0,len));  Filereader.close ();  Filewriter.close ();

Run:



② The implementation of File replication:

There are two kinds, as you choose.

Method 1:

FileReader FileReader = new  FileReader ("D:/one.txt"); FileWriter FileWriter = new FileWriter ("E:/one.txt");//The simplest notation for copying files char [] cbuf=new char[1024]; Character array          int len=filereader.read (CBUF);          Filewriter.write (CBUF);        Filereader.close (); Filewriter.close ();


Method 2:

FileReader FileReader = new  FileReader ("D:/one.txt"); FileWriter FileWriter = new FileWriter ("E:/one.txt"); char []buf = new char[1024];          int len = 0;          Read an array size and write an array size method.          while (len = Filereader.read (BUF))! =-1) {          filewriter.write (buf, 0, Len);                        }  Filereader.close (); Filewriter.close ();

③ to be aware of:

When using FileWriter, pay attention to:

FileReader and FileWriter read and write files are the platform default encoding (depending on the operating system), such as the Chinese win for GBK,

The English win is the ISO, when the text file encoding to be written and the platform default encoding is inconsistent, there will be a case of Chinese garbled.

This can be read by OutputStreamWriter. This will say, MO-Hurry ~




3.CharArrayReader and Chararraywriter class:

Before we learned the Chararrayinputstream and the Chararrayoutputstream class, actually is similar, but this

is a character, the front two is a byte, also he has a ToCharArray () Method! There is nothing to talk about, not much to use,

But also with other flows.

Here is a simple example of writing data to a file:

Chararraywriter f = new Chararraywriter ();  String str = "Just a few, sleep you numb, get up Hey ~";  char []BUF1 = new Char[str.length ()];  Str.getchars (0, Str.length (), BUF1, 0);  Write buffer  f.write (BUF1);  Char c[] = F.tochararray ();  FileWriter F2 = new FileWriter ("D:/test.txt");  F.writeto (F2);  F2.close (); }

after running, you can see the D drive to generate a test.txt file, it feels better to use the FileWriter directly




4.PipedReader and PipedWriter

This and the previous PipedInputStream and PipedWriter are similar, the only difference is

byte[] became char[]! the code just changed a little bit more than before

Import Java.io.ioexception;import Java.io.pipedoutputstream;import Java.io.pipedwriter;public class SendThread Extends thread{private pipedwriter out = new PipedWriter ();   Public PipedWriter Getoutputstream () {           return out;       }   public void Run () {           String message = "I am pipedwriter write something";           try {               out.write (Message.tochararray ());               Out.close ();           } catch (IOException e) {               e.printstacktrace ();}}   }

Import Java.io.ioexception;import Java.io.pipedinputstream;import Java.io.pipedreader;public class ReceiverThread Extends Thread {private Pipedreader in = new Pipedreader ();p ublic pipedreader getInputStream () {return in;} public void Run () {char[] buf = new Char[1024];try {int len = In.read (BUF);//print another thread input stream System.out.println (new String (buf , 0, Len)); In.close ();} catch (IOException e) {e.printstacktrace ();}}}

Import Java.io.ioexception;import Java.io.pipedinputstream;import Java.io.pipedoutputstream;import Java.io.pipedreader;import Java.io.pipedwriter;public class Test5 {public static void main (string[] args) { Receiverthread rthread = new Receiverthread (); Sendthread sthread = new Sendthread ();//Get the corresponding stream: PipedWriter out = Sthread.getoutputstream (); Pipedreader in = Rthread.getinputstream (); try {//Pipe link out.connect (in); Sthread.start (); Rthread.start ();} catch ( IOException e) {e.printstacktrace ();}}}

Run:




5.InputStreamReader and Inputstreamwriter

These two streams are streams of byte-stream and character streams, but one thing to note is that these two things are:

FileReader and FileWriter's parent class;

The former is a subclass of reader, the input byte to the character stream of the bridge;

The latter is the writer's subclass, the output character flows to the word stream the bridge!

So no matter what we do, it's finally saved in bytes in the file!!!

As for setting the encoding, you can define it directly in the construction method:


Like what:

New InputStreamReader (New FileInputStream ("D:\\books.txt"), "UTF-8");


Well, let's write a simple example:

public static void Main (string[] args) throws Exception {String filename1 = "D:/file.txt"; String filename2 = "d:/copy-file.txt"; InputStreamReader ISR = new InputStreamReader (new FileInputStream (filename1), "GBK" ); OutputStreamWriter OSW = new OutputStreamWriter (new FileOutputStream (filename2), "GBK"); int ch = 0;while ((ch = isr.read ())! =-1) {System.out.print ((char) ch); osw.write (ch);} System.out.println ("\ n file copy complete"); Isr.close (); Osw.close ();}




Finally say two words:


OK, about the byte stream in Java IO here, the next section we're going to learn is the buffer stream,

Finally, we review the following sections:

①reader class and writer class related methods:

②2.FileReader and FileWriter class use: File read and write, but they are ⑤ subclass Oh!

③CharArrayReader and Chararraywriter class: Character array class, which is used to buffer the character array;

④Pipedreader and PipedWriter class: Pipe character class, pass the word Fu Yi ~

⑤InputStreamReader and Inputstreamwriter: The conversion stream of characters and bytes, is the parent class of ②, all files are in bytes

Stream in the form of stored oh, whether you are using FileInputStream, or ②⑤, the results are the same ~

PS: In fact, the content of this section and Part 3, only the byte changed to a character only ~





J2SE Knowledge points inductive note (vii)---Java IO Part 4: Basic character stream

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.