The Dark Horse Programmer------The summary of IO stream learning in Java

Source: Internet
Author: User

Java training, Android training, iOS training,. NET training. Looking forward to your communication

First, the concept

Flow: A stream is an abstraction of a sequence of bytes, a data source that can be continuously read, and a stream that can be continuously written to the data.

IO stream: Used to process data on the device

Common equipment: Hard disk, memory, keyboard input, etc.

Classification of IO streams:

1, according to the processing data types, can be divided into byte stream and character stream.

The origin of the character stream: Because of the different file encoding, but with the character of the efficient operation of characters stream object, the principle is based on byte stream reading bytes, to check the relevant code table.

The difference between a character stream and a byte stream:

* * Byte stream read, read a byte to return a bytes, and the character stream is a byte stream read one or more bytes at a time, and then go to the corresponding Code table, will find the characters returned.

* * The byte stream can handle all data types, whereas a character stream will only handle character data.

2, according to the flow of different flows, can be divided into input stream and output stream.

II: IO system inheritance Diagram

Three: function

The IO system has the most basic two functions: Read and write.

1, Byte stream: InputStream (Read) and OutputStream (write).

2, Character stream: Reader (read) and writer (write).

Character Stream Basic read and write operations:

Read Reader and writer first

Inheritance Relationship:

Reader

InputStreamReader

FileReader: A character read stream object dedicated to processing files

Writer

Outputstreamreader

FileWriter: Writes a Stream object specifically for processing the file's characters

Common methods in Reader:

1, int read (): reads a character and returns the character read. Returns 1 if the end of the stream has been read;

2, int Raad (char[]): The read to the character into the specified array of characters, return the number of characters read, if you have read to the end of the stream, then return-1;

3. Close (): Close the stream and release the resource.

Common methods in Writer:

1. Write (CH): writes a character to the stream.

2. Write (char[]): Writes a character array to the stream.

3. Write (String): Writes a string to the stream.

4. Flush (): Flushes the data in the stream to the data destination, and the stream still exists.

5, Close (): Close the stream. The data in the stream is flush () into the data destination before the resource is closed.

FileReader:

1. The stream object used to read the text file.

2, for associating text file.

Constructor: FileReader (String fileName);

When the read stream object is initialized, a read file must be specified.

FileNotFoundException occurs if the file does not exist

FileWriter:

1. For working with text files

2. There is a default encoding table in this class

3. There is a temporary buffer in this class

Constructor: FileWriter (String fileName)

When writing to the stream object initialization, you must specify a destination to store the data.

If the file does not exist, the system creates a file.

If the file exists, it will be overwritten.

FileWriter (String filename,boolean Append):

When Append is true, the data continues to be written at the end of the file.

code example:

Copy the C-drive text file to the D drive. /* The principle of copying: In fact, the C disk under the file data is stored in a file d. Step: 1, create a file in the D drive. Used to store data in a C-drive file. 2, define read stream and C-Drive file association. 3, through continuous reading and writing to complete the data storage. 4, close the resource.    */import java.io.*;class copytext {public static void main (string[] args) throws IOException {copy_2 ();        public static void Copy_2 () {FileWriter FW = null;        FileReader FR = null;            try {fw = new FileWriter ("Systemdemo_copy.txt");            FR = new FileReader ("Systemdemo.java");            char[] buf = new char[1024];            int len = 0;            while ((Len=fr.read (BUF))!=-1) {fw.write (Buf,0,len);        }} catch (IOException e) {throw new RuntimeException ("Read and Write Failed");                } finally {if (fr!=null) try {fr.close ();                } catch (IOException e) {} if (Fw!=null)        try {            Fw.close ();    } catch (IOException e) {}}}//read a character from the C drive and write a character to the D drive.        public static void Copy_1 () throws IOException {//create destination.        FileWriter FW = new FileWriter ("Runtimedemo_copy.txt");        Associated with an existing file.        FileReader FR = new FileReader ("Runtimedemo.java");        int ch = 0;        while ((Ch=fr.read ())!=-1) {fw.write (CH);        } fw.close ();    Fr.close (); }}

The buffer of the character stream:

The presence of buffers increases the operational efficiency of the convection, and the principle of its implementation is to encapsulate the internal array.

The corresponding object:

BufferedReader

Unique method: ReadLine (): reads one line at a time, reads the line tag, returns the string before the row tag, and returns NULL when the end is read.

BufferedWriter

Unique method: NewLine (): cross-platform newline character, used to write a newline character into the stream.

Text-Copy code using buffer technology:

/* Copy A. java file through a buffer. */import java.io.*;class copytextbybuf{public static void Main (string[] args) {BufferedReader bufr = null        ;        BufferedWriter BUFW = null;            try {bufr = new BufferedReader (New FileReader ("Bufferedwriterdemo.java"));            BUFW = new BufferedWriter (New FileWriter ("Bufwriter_copy.txt"));            String line = null;                while ((Line=bufr.readline ())!=null) {bufw.write (line);                Bufw.newline ();            Bufw.flush ();        }} catch (IOException e) {throw new RuntimeException ("Read and Write Failed");            } finally {try {if (bufr!=null) bufr.close ();            } catch (IOException e) {throw new RuntimeException ("Read shutdown failed");            } try {if (bufw!=null) bufw.close ();  }          catch (IOException e) {throw new RuntimeException ("Write shutdown failed"); }        }    }}

Read and write operation for byte stream:

Abstract accumulation: InputStream and OutputStream

A byte stream can manipulate any data.

Also, take the code for the buffer to copy a section of the MP3 file as an example:

/* Demo copy of MP3. Through the buffer. Bufferedoutputstreambufferedinputstream to simplify the code, throw the exception. */import java.io.*;class copymp3{public static void Main (string[] args) throws IOException {Long start = S        Ystem.currenttimemillis ();        Copy_2 ();        Long end = System.currenttimemillis ();    System.out.println ((End-start) + "MS");  } public static void Copy_2 () throws IOException {Mybufferedinputstream Bufis = new Mybufferedinputstream (new        FileInputStream ("C:\\9.mp3"));                Bufferedoutputstream Bufos = new Bufferedoutputstream (New FileOutputStream ("C:\\3.mp3"));        int by = 0;        System.out.println ("First byte:" +bufis.myread ());        while ((By=bufis.myread ())!=-1) {bufos.write (by);        } bufos.close ();    Bufis.myclose ();    ///buffer through byte stream to complete replication. public static void Copy_1 () throws IOException {Bufferedinputstream Bufis = new Bufferedinputstream (New Fileinpu        TStream ("C:\\0.mp3")); Bufferedoutputstream Bufos = nEW Bufferedoutputstream (New FileOutputStream ("C:\\1.mp3"));        int by = 0;        while ((By=bufis.read ())!=-1) {bufos.write (by);        } bufos.close ();            Bufis.close (); }}

Conversion Flow:

Characteristics:
1. Is the bridge between the byte stream and the character stream.
2, the Stream object can be read to the byte data to the specified encoding table encoding conversion.

When do you use it?
1. When there is a conversion action between the byte and the character.
2, stream operation of the data needs to be encoded when the table is specified.

The specific object embodies:
1, InputStreamReader: byte-to-character bridge.
2, OutputStreamWriter: The character to the byte of the bridge.

constructor function:
InputStreamReader (InputStream): Through this constructor initialization, using the system is the default encoding table GBK.
InputStreamReader (inputstream,string charSet): Through this constructor initialization, you can specify the encoding table.
OutputStreamWriter (OutputStream): Through this constructor initialization, using the system is the default encoding table GBK.
OutputStreamWriter (outputstream,string charSet): Through this constructor initialization, you can specify the encoding table. The character stream object of an action file is a subclass of the transform stream.

The Read method in the transform stream. has been integrated into the Code table, the underlying invocation of the Read method of the byte stream will fetch one or more bytes of data to be stored temporarily, and to check the specified encoding table, if the encoding table is not specified, check the default Code table. Then the Read method of the stream can return a character such as Chinese. The conversion stream has completed the encoding conversion action, for the direct operation of the text file of the Filereaer, it is not redefined, as long as the transformation stream, to obtain its method, you can directly manipulate the text file in the character data.

Summary: Basic rules of flow operations:

1, clear data source and data purposes. In fact, the input stream or output stream is defined.

2, the clear operation of the data is plain text data. In fact, it is to clarify the character stream or byte flow.

Data Source: Keyboard system.in, hard disk (stream object at the beginning of file), memory (array).

Data purpose: Console System.out, hard disk (stream object at the beginning of file), memory (array).

The Dark Horse Programmer------The summary of IO stream learning in Java

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.