The choice of which object is a problem for many people when using IO streams. Answer the question by a sequence of judgments and cases.
First, introduce a brief introduction to the flow
Stream can be divided into character stream and byte stream type
The byte stream corresponds to Inputsteam (input stream) and OutStream (output stream).
The character stream corresponds to reader (input stream) and writer (output stream).
Two: Introduce the selection rule (1) through the device input stream now
Select InputStream if the input stream is byte.
Select Reader if the input stream is plain text.
(2) determine the output stream through the device
If the output stream is byte, select OutputStream.
If the output stream is plain text, select Writer.
Three: Now use an example to show the above rules
Requirements: Print the contents of a text file through the console.
1. A text file is a plain text file
So the input stream is reader
The class that operates the file in reader is FileReader
So filereader fd = new FileReader ("123.txt");
To improve read efficiency, use the buffer
So BufferedReader BRD = new BufferedReader (reader);
2. Read plain text, so the output stream uses writer
And the console output System.out is a byte stream
So you need to change the character stream into a byte stream for output.
So choose Convert Stream OutputStreamWriter
OutputStreamWriter out = new OutputStreamWriter (system.in);
To increase efficiency, use the BufferedWriter
So: bufferedwriter BRW = new BufferedWriter (out);
The following is a sample code
1 PackageCom.sjj.io;2 3 ImportJava.io.BufferedReader;4 ImportJava.io.BufferedWriter;5 ImportJava.io.FileReader;6 Importjava.io.IOException;7 ImportJava.io.OutputStreamWriter;8 9 Public classTest01 {Ten One A Public Static voidMain (string[] args) { -BufferedReader BRD =NULL; -BufferedWriter BRW =NULL; the Try { -BRD =NewBufferedReader (NewFileReader ("D:\\fileio.txt")); -BRW =NewBufferedWriter (NewOutputStreamWriter (System.out)); -String str =NULL; + while(str = brd.readline ())! =NULL){ - brw.write (str); + brw.newline (); A Brw.flush (); at } -}Catch(IOException e) { - //TODO auto-generated Catch block - e.printstacktrace (); -}finally{ - if(BRD! =NULL) { in Try { - brd.close (); to}Catch(IOException e) { + //TODO auto-generated Catch block - e.printstacktrace (); the } * } $ if(BRD! =NULL) {Panax Notoginseng Try { - brw.close (); the}Catch(IOException e) { + //TODO auto-generated Catch block A e.printstacktrace (); the } + } - } $ $ } - -}
View Code
Which stream object to select when using IO stream