Knowledge points for character streams in Java---IO Learning notes (iii)

Source: Internet
Author: User

Character Stream:

the difference between text and text files:
Text:
The Java text (char) is a 16-bit unsigned integer, which is the Unicode encoding of the character (double-byte encoding).
File:
File is a byte of byte byte ... Data series.
Text file:
A text file is a stored result of a sequence of text (char) serialized into Byte according to an encoding scheme (UTF-8,UTF-16BE,GBK).

character Stream (Reader,writer)
The action is a text file. For MP3, a binary file is a byte file that is not suitable for a character stream to read because the read is char and has no meaning.
Processing of characters, one character at a time
The bottom of the character is still the basic byte sequence

the basic implementation of a character stream (Byte character translation stream):
InputStreamReader:
Completes a byte stream parsing to a char stream, parsed by encoding
Outstreamwriter:
Provides a char stream to a byte stream, which is processed by encoding

Use of the basic method of character stream:

 PackageCom.test.FileInputStreamReader;ImportJava.io.FileInputStream;ImportJava.io.IOException;ImportJava.io.InputStreamReader; Public  class fileinputstreamreadertest {     Public Static void Main(string[] args) {Try{String filename ="c:\\users\\administrator\\desktop\\javaio\\ read test file. txt";            ReadFile1 (filename);        ReadFile2 (filename); }Catch(Exception e)        {E.printstacktrace (); }    }/** * Single character read * Returns the value of the read to byte converted to int type (last 8 bits) * @param FIS */     Public Static void ReadFile1(String filename)throwsioexception{System.out.println ("single-byte reads:"); InputStreamReader ISR =NewInputStreamReader (NewFileInputStream (filename));//default is the code for the project (this is GBK)//InputStreamReader ISR = new InputStreamReader (FIS, "GBK");        intI while((i = Isr.read ())!=-1) {System.out.print (Char) (i);    } isr.close (); }/** * Bulk Read * Put in BUF this character array, starting from the No. 0 position, placing up to Buf.length * Return is the number of read characters * @param fis * @thr OWS IOException * /     Public Static void ReadFile2(String filename)throwsioexception{System.out.println (); System.out.println ("Bulk Read mode:"); InputStreamReader ISR =NewInputStreamReader (NewFileInputStream (filename));//default is the code for the project (this is GBK)        Char[] buf =New Char[2*1024x768];intI while((i = Isr.read (buf,0, buf.length))!=-1){//// The first type of conversion into characters//for (int j = 0;j<i;j++) {//System.out.print ((char) buf[j]);//          }            //The second way of converting to a stringString str =NewString (BUF,0, i);        System.out.println (str);    } isr.close (); }}

Results:

Note: When manipulating character streams, be aware of the coding problem. The file read here is in GBK encoded format, so it should be read with GBK encoding. Otherwise, garbled characters will appear.

FileWriter and FileReader:
In fact, the above code:
InputStreamReader ISR = new InputStreamReader (new FileInputStream (String filename);
This part of the code can be used completely
FileReader FR = new FileReader (String filename);
To replace.
Use of the basic methods of FileReader and FileWriter:

 PackageCom.test.FileReaderAndFileWriter;ImportJava.io.FileReader;ImportJava.io.FileWriter;ImportJava.io.IOException; Public  class filereaderandfilewritertest{     Public Static void Main(string[] args)throwsioexception{FileReader FR =NewFileReader ("c:\\users\\administrator\\desktop\\javaio\\ read test file. txt");//Cons: But only the project can be identified by default encoding cannot be set other encoding, if the read file encoding is not the default encoding of the project, the reading will appear garbledFileWriter FW =NewFileWriter ("test file written by c:\\users\\administrator\\desktop\\javaio\\. txt");Char[] buf =New Char[2*1024x768];intI while((i = Fr.read (buf,0, buf.length))!=-1) {Fw.write (buf,0, i);        Fw.flush ();        } fr.close ();    Fw.close (); }}

Note: FileReader and FileWriter are simpler than the InputStreamReader wrapper FileInputStream in the previous code, but they cannot be set to read files using the default encoding of the project.

Filter for character streams:
Bufferedreader-->readline read one line at a time
Bufferedwriter/printwriter ——— > Write a line

 PackageCom.test.BufferedReaderAndBufferedWriter;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter;ImportJava.io.PrintWriter; Public  class bufferedreadertest {     Public Static void Main(string[] args) {String filename ="c:\\users\\administrator\\desktop\\javaio\\ read test file. txt";Try{bufferedwriter (filename);        PrintWriter (filename); }Catch(IOException e)        {E.printstacktrace (); }    }/** * Write with BufferedWriter * @throws ioexception * *     Public Static void BufferedWriter(String filename)throwsioexception{BufferedReader br =NewBufferedReader (NewInputStreamReader (NewFileInputStream (filename)); BufferedWriter BW =NewBufferedWriter (NewOutputStreamWriter (NewFileOutputStream ("c:\\users\\administrator\\desktop\\javaio\\ test file 1.txt"))); String Line; while(line = Br.readline ())! =NULL){//But the readline here do not recognize line breaksSystem.out.println (line);///Bw.write (line);//write the file content is not wrapped///Bw.write (line+ "\ r \ n");//write a separate line operation when you write the file hereBw.write (line); Bw.newline ();//Line break OperationBw.flush ();        } br.close ();    Bw.close (); }/** * Write with PrintWriter * @param filename * @throws ioexception * *     Public Static void PrintWriter(String filename)throwsioexception{BufferedReader br =NewBufferedReader (NewInputStreamReader (NewFileInputStream (filename)); PrintWriter PW =NewJava.io.PrintWriter ("c:\\users\\administrator\\desktop\\javaio\\ test file 2.txt"); String Line; while(line = Br.readline ())! =NULL) {pw.println (line);        Pw.flush ();        } br.close ();    Pw.close (); }}

The effect of the two methods of writing a file above is the same.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Knowledge points for character streams in Java---IO Learning notes (iii)

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.