Java---io enhancement (2)

Source: Internet
Author: User

Convert stream ★ Convert stream function 1: Serves as a bridge between a byte stream and a character stream

Requirements: Analog English Chat program, requirements:
(1) From the keyboard input English characters, each record line to turn it into uppercase output to the console;
(2) Save the chat log to the byte stream file.

Design analysis of Requirement 1:

1) need to receive input from the keyboard, with system.in, it is byte input stream inputstream;
2) need to handle characters, you can turn the byte strong into characters, you can also use character stream;
3) A function similar to ReadLine is required, and this method is available in character stream BufferedReader (and the class has buffer growth).
In conclusion, it is reasonable to use the conversion stream to transfer bytes into character stream, that is, using InputStreamReader

Design analysis of Requirement 2:

1) The character data needs to be saved to the byte stream file by line;
2) The character stream adopts bufferedwriter more suitable, because it has newline method and can achieve high efficiency;
3) Byte stream file, use FileOutputStream.
In conclusion, it is reasonable to use the conversion flow to convert character stream into a byte throttle, that is, using OutputStreamWriter

Code implementation:

 PackageIo.transfer;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.OutputStreamWriter; Public classTranstreamdemo { Public Static voidMain (string[] args) throws IOException {//InputInputStreaminch= System.inch; InputStreamReader ISR =NewInputStreamReader (inch); BufferedReader br =NewBufferedReader (ISR);//OutputOutputStream out=NewFileOutputStream ("Chat.txt"); OutputStreamWriter OSW =NewOutputStreamWriter ( out); BufferedWriter BW =NewBufferedWriter (OSW); String line =NULL; while((Line=br.readline ())! =NULL){if("Over". Equals (line)) {//Develop good code habits: When invoking a method in string, put the constant string in front, preventing the variable from being null and causing the exception                 Break; } System. out. println (Line.touppercase ());            Bw.write (line);            Bw.newline (); Bw.flush ();//character stream is buffered and must be brushed and buffered}    }}
Convert stream

(InputStreamReader and OutputStreamWriter)

★ Conversion Stream Function 2: Character encoding conversion

Use FileWriter to encode by default
fileoutputstream+ Default Encoding Table

Using the conversion stream to encode by default
OutputStreamWriter + fileoutputstream + default encoding table

Using the conversion stream to specify encoding coding
OutputStreamWriter + fileoutputstream + specified encoding table

Use the conversion stream to decode the specified encoding
InputStreamReader + fileinputstream + specified encoding table

Code implementation:
 PackageIo.transfer;ImportJava.io.FileInputStream;ImportJava.io.FileNotFoundException;ImportJava.io.FileOutputStream;ImportJava.io.FileReader;ImportJava.io.FileWriter;ImportJava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter; Public  class TranStreamDemo2 {     Public Static void Main(string[] args) {Try{//readtextdecoding1 ();            //readtextdecoding2 ();Writetextencoding (); }Catch(IOException e)        {E.printstacktrace (); }    }Private Static void writetextencoding()throwsIOException {///First type: filewriter+ default encoding TableFileWriter FW =NewFileWriter ("Files\\w_utf-8.txt");//The encoding of the file is determined by the platform (e.g. MyEclipse or DOS window), not necessarily utf-8Fw.write ("A little progress every day ..."); Fw.close ();///second type: outputstreamwriter+ default encoding TableOutputStreamWriter OSW =NewOutputStreamWriter (NewFileOutputStream ("Files\\w_utf-8_2.txt"));//The encoding of the file is determined by the platform (e.g. MyEclipse or DOS window), not necessarily utf-8Osw.write ("The first day of progress ...");//Osw.close ();//Third type: outputstreamwriter+ Specify the Encoding tableOutputStreamWriter OSW2 =NewOutputStreamWriter (NewFileOutputStream ("Files\\w_utf-8_3.txt"),"Utf-8");//The encoding of the file must be utf-8, because it is our own designationOsw2.write ("The first day of progress ...");    Osw2.close (); }Private Static void readTextDecoding1()throwsIOException {FileReader FR =NewFileReader ("Files\\utf-8.txt");//decoding with default encoding table        Char[] Cbuf =New Char[Ten];intlen=0; while((Len=fr.read (CBUF))!=-1) {String str =NewString (Cbuf,0, Len);        System.out.print (str);    } fr.close (); }Private Static void readTextDecoding2()throwsIOException {//inputstreamreader ISR = new InputStreamReader (New FileInputStream ("Files\\gbk.txt"));//If you do not specify an encoding table, use the default        //Use the conversion stream to specify the decoding table----as long as the encoding table of the file is the same as the decoder table specified here, there will be no garbled        //inputstreamreader ISR = new InputStreamReader (New FileInputStream ("Files\\gbk.txt"), "GBK");//ok        //inputstreamreader ISR = new InputStreamReader (New FileInputStream ("Files\\utf-8.txt"), "GBK");//garbledInputStreamReader ISR =NewInputStreamReader (NewFileInputStream ("Files\\utf-8.txt"),"Utf-8");//ok        Char[] Cbuf =New Char[ -];intLen = Isr.read (CBUF); String str =NewString (Cbuf,0, Len);        System.out.println (str);    Isr.close (); }}
Print flow ★ Print Flow Features:

1) Only the output is not entered. PrintStream is a byte print stream, and PrintWriter is a character print stream.
2) It is easy to print a variety of data "value representations", providing a series of printing functions (only it has, no other flow.) )
3) Unlike other output streams, it never throws an IOException exception (except for the construction method), internally resolves the exception and sets the internal flag.
4) You can create a feature with automatic refresh that uses the println () method with line breaks.
5) (in the constructor method) you can specify the character set encoding.

★ About automatic refresh of the print stream

Autoflush-boolean variable; If true, the println, printf, or Format method refreshes the output buffer.
* * Actually because these methods help us call the Out.flush ().

Code implementation:

Demonstrates the automatic refresh feature of the PrintStream class
 PackageIo.print;ImportJava.io.FileNotFoundException;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.PrintStream;/** * * @author Chen Haoxiang * * 2016-4-24 * *//Demo auto Refresh function of PrintStream class Public  class printstreamdemo {     Public Static void Main(string[] args) {Try{demo1 (); Demo2 (); for(intI=0;i<Ten; i++) {System.out.println (i); }//The screen terminal will not have output because the Demo2 () is running;            //Change the System.out output destination from the screen to the log file}Catch(IOException e)        {E.printstacktrace (); }    }//Change the System.out output destination from the screen to the log file    Private Static void Demo2()throwsIOException {FileOutputStream Font =NewFileOutputStream ("Log.txt"); PrintStream out =NewPrintStream (Font,true);    System.setout (out); }Private Static void Demo1()throwsIOException {PrintStream out =NewPrintStream ("Print.txt");//out.write () writes only one byte (binary 8 bits) of information, if the parameter is greater than the range of one byte,        //Then only the last byte of data is actually writtenOut.write ( the); Out.write (353);///The last byte is 97, so write a character ' a '----write a value representationSystem.out.write (353);//Output ' a 'System.out.flush (); Out.println (345);//Convert parameters to string output        //Previous sentence equivalent to Out.write (string.valueof (i))        //※ in short, the byte data is output in PrintStream with write () and only one byte at a time, and print () outputs the representation of the value of the data into a string output.         The Out object in//jsp is this type. To output a binary format such as a byte slice declaration, you must use Write (), and the output page data (character) is printed () or println ()}}
Demonstrates the automatic refresh feature of the PrintWriter class
 PackageIo.print;ImportJava.io.IOException;ImportJava.io.PrintWriter;/** * * @author Chen Haoxiang * * 2016-4-24 * *//Demo auto Refresh function of PrintWriter class Public  class PrintStreamDemo2 {     Public Static void Main(string[] args) {demo1 ();Try{Demo2 (); }Catch(IOException e)        {E.printstacktrace (); }    }Private Static void Demo1() {//default does not automatically refresh thePrintWriter out =NewPrintWriter (System.out); Out.print ("Hello World");//Does not refresh automaticallyOut.println ("Hello World");//Does not refresh automaticallyOut.flush ();//Manual Refresh}Private Static void Demo2()throwsIOException {//Set auto-RefreshPrintWriter out =NewPrintWriter (System.out,true); Out.print ("Hello World");//Does not refresh automaticallyOut.println ("Hello World");//Will----because Out.flush () is called internally by println ()Out.print ("Hello3 \ n");//Will notOut.print ("Hello3 \ r \ n");//Will notout.printf ('%s ',"Hello4");//Will        /* in SUMMARY: * Autoflush-boolean variable; If true, the println, printf, or Format method refreshes the output buffer.         *---is actually because these methods help us call Out.flush (). */}}

The following three of the other streams in the IO package are memory arrays:

★ Byte Array Stream
Bytearrayinputstream and Bytearrayoutputstream

★ Character Array Stream
CharArrayReader and Chararraywriter

★ String Stream
StringReader and StringWriter

1, the Flow object for manipulating byte arrays, in fact, they are the corresponding device is the memory stream object.
2, the shutdown of the stream is invalid because no system resources have been called.
3. Manipulate the elements in the array according to the reading and writing thoughts of the stream.

★ Sequence Stream
SequenceInputStream  ——对多个流进行合并

logical concatenation of multiple streams (merging into one stream makes it convenient to operate because multiple sources become a source)

Summary of IO stream knowledge points

The stream is used to process the data.
When working with data, be sure to first identify the data source and data destination (data sinks).
The data source can be a file, keyboard, or other stream.
The data destination can be a file, monitor, or other stream.
Flow is only to help the data transfer, and the transmission of data processing, such as filtering processing, conversion processing and so on.

★io Flow System

Key points of use: Look at the top level (the parent generic feature), with the underlying (subclass specific object).

Naming laws:

The suffix of each subclass is the name of the parent class of the owning system, and it is easy to distinguish between the owning system.
And each sub-class prefix is the function of the subclass object.

Mastering the main points and rules of Io flow system, it is much easier to design and find the corresponding classes at development time.

Java---io enhancement (2)

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.