java--(ix) IO stream

Source: Internet
Author: User

First, the classification of the flow

Input stream and output stream

It can be divided into input stream and output stream according to flow direction.

    • Input stream: Data can only be read from and not written to.
    • Output stream: Data can only be written to and not read from.

The input and output here involve a directional problem, data from memory to hard disk, often referred to as the output stream. (That is, this

The input and output are separated from the memory in which the program is running. The input stream of Java is mainly composed of InputStream and

Reader is the base class, and the output stream is made up of OutputStream and writer as the base class. They are all abstract base classes

, you cannot create an instance directly.

Byte Stream and character stream

byte streams and character streams are used almost the same way, except that the data units they manipulate are different, and the data units of the byte stream operations

is 8 bits, and the data unit of the character stream operation is 16 bits. Byte stream should be used as base class by InputStream and OutputStream

, and the character stream is made up of reader and writer as the base class.

node flow and processing flow

According to the role of the stream, it can be divided into node stream and processing stream.

A stream that can read/write data from a specific IO device is called a node stream, and a node stream is also known as a low-level stream. When you use a node

Stream for input/output, the program connects directly to the actual data source, and the actual input/output node is connected.

The processing stream is used to connect or encapsulate an existing stream, and to implement the data read/write function through the encapsulated stream. Secretariat

The flow of management is also known as Advanced streaming and wrapper flow.

One obvious benefit of using the process flow is that the program can take exactly the same input/

The output code accesses different data sources, and as the flow of the nodes in the processing stream changes, the data source that the program actually accesses is correspondingly

Changes in the ground.

The conceptual model of flow

    • Inputstream/reader: The base class for all input streams, which is the byte input stream, which is the character input stream.
    • Outputstream/writer: The base class for all output streams, which is the byte output stream, which is the character output stream.

The following procedure demonstrates the use of FileInputStream to read its own effect:

1 Package IO;2 3 import Java.io.FileInputStream;4 import java.io.IOException;5 6  Public classFileinputstreamtest {7 8      Public Static voidMain (string[] args) throws IOException {9 Ten         //Create a byte input stream OneFileInputStream FIS =NewFileInputStream ("D:\\java\\adt-bundle-windows-x86_64_20140101\\project\\fsad\\src\\io\\fileinputstreamtest.java"); A          -         //create a byte array of length 1024 -         byte[] buf =New byte[1024x768]; the         intLen =0; -          -          while(len = Fis.read (buf)) >0 ) { -             //Remove bytes from buf, convert byte array to string input +System. out. println (NewString (BUF,0, Len)); -         } + fis.close (); A     } at  -}

Operation Result:

Package io;import Java.io.fileinputstream;import java.io.IOException; Public classFileinputstreamtest { Public Static voidMain (string[] args) throws IOException {//Create a byte input streamFileInputStream FIS =NewFileInputStream ("D:\\java\\adt-bundle-windows-x86_64_20140101\\project\\fsad\\src\\io\\fileinputstreamtest.java"); //create a byte array of length 1024        byte[] buf =New byte[1024x768]; intLen =0;  while(len = Fis.read (buf)) >0 ) {            //Remove bytes from buf, convert byte array to string inputSystem. out. println (NewString (BUF,0, Len));    } fis.close (); }}

The above program creates a byte array of length 1024 to read the file, which is actually less than 1024 of the length of the Java source file

Bytes, that is, the program simply executes a read () method to read the entire content. But if you create a byte array of a smaller length, the program

The runtime can be garbled when outputting Chinese annotations, because the file is saved with GBK encoding, in this way, each

The Chinese character takes up 2 bytes, and if the Read () method reads only half of the Chinese characters, this results in garbled characters.

Java7 rewrites all the IO resource classes, all of which implement the Autocloseable interface, so all can be closed by automatically closing the resource

The try statement to close these IO streams. The following program uses FileReader to read the file itself.

1  PackageIO;2 3 ImportJava.io.FileReader;4 Importjava.io.IOException;5 6  Public classFilereadertest {7 8      Public Static voidMain (string[] args) {9 Ten         Try ( One         //creating a character input stream AFileReader FR =NewFileReader ( -"D:\\java\\adt-bundle-windows-x86_64_20140101\\project\\fsad\\src\\io\\filereadertest.java")) { -             //create a character array of length 32 the             Char[] Cbuf =New Char[32]; -             intLen = 0; -  -              while(len = Fr.read (cbuf)) > 0) { +System.out.println (NewString (cbuf, 0, Len)); -             } +}Catch(IOException e) { A             //TODO auto-generated Catch block at e.printstacktrace (); -         } -     } -  -}

Operation Result:

 PackageIO;ImportJava.io.FileReader;Importjava.io.IOException; Public classFilereadertest { Public Static voidMain (string[] args) {Try (        //creating a character input streamFileReader FR =NewFileReader ("D:\\java\adt-bundle-windows-x86_64_20140101\\project\\fsad\\src\\IO\\FileReaderTest.java")) {//Create aa character array of length 32Char[] Cbuf =NewChar[32]; intLen = 0;  while(len =Fr.read (cbuf))> 0) {System.out.println (new String (Cbuf,0, Len)); }        } Catch(IOException e) {//TODO auto-generated catch block e.printstacktrace (); }    }}

The following program uses FileInputStream to perform the input and uses FileOutputStream to perform the output.

1  PackageIO;2 3 ImportJava.io.FileInputStream;4 ImportJava.io.FileOutputStream;5 Importjava.io.IOException;6 7  Public classFileoutputstreamtest {8 9      Public Static voidMain (string[] args) {Ten  One         Try { A             //Create a byte input stream -FileInputStream FIS =NewFileInputStream ( -"D:\\java\\adt-bundle-windows-x86_64_20140101\\project\\fsad\\src\\io\\fileoutputstreamtest.java"); the             //creating a byte output stream -FileOutputStream fos =NewFileOutputStream ("NewFile.txt"); -  -             byte[] buf =New byte[32]; +             intLen = 0; -  +              while(len = Fis.read (buf)) > 0) { AFos.write (buf, 0, Len); at             } -}Catch(IOException e) { -  - e.printstacktrace (); -         } -System.out.println ("Write succeeded! "); in     } -}

Operation Result:

Write Success!

The following is an example of getting keyboard input to introduce the transformation stream. Java uses system.in to represent standard input, which is keyboard input, but this standard output

The inflow is an instance of the InputStream class, is not easy to use, and the keyboard input is text, so you can use InputStreamReader

Convert it into a character input stream reader, and then wrap the normal reader into BufferedReader, using the BufferedReader ReadLine () method

One line of content can be read at a time. The procedure is as follows:

1  PackageIO;2 3 ImportJava.io.BufferedReader;4 Importjava.io.IOException;5 ImportJava.io.InputStreamReader;6 7  Public classKeyintest {8 9      Public Static voidMain (string[] args) {Ten  One         //converts a System.in object into a reader object and then wraps it into a bufferedreader ABufferedReader br =NewBufferedReader (NewInputStreamReader (system.in)); -  -String buffer =NULL; the  -         Try { -              while(buffer = Br.readline ())! =NULL) { -                 //if "Exit" is read to the string, the program exits +                 if(Buffer.equals ("Exit")) { -System.exit (1); +                 } ASYSTEM.OUT.PRINTLN ("Input content:" +buffer); at             } -}Catch(IOException e) { -             //TODO auto-generated Catch block - e.printstacktrace (); -         } -     } in  -}

Operation Result:

The Dark Horse programmer entered the content: Dark Horse programmer exit

The BufferedReader stream has buffering capabilities, which can read one line of text at a time-with a newline character as a flag, if not read

NewLine characters are blocked by the program until a newline character is read.

java--(ix) IO 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.