Black Horse programmer _javaio Flow Overview

Source: Internet
Author: User

-------Android Training, Java training, look forward to communicating with you! ----------

I. Overview of IO Streams

(1)

IO streams are used to process data transfer between devices
The Java operation of the data is streamed through the way
The objects that Java uses to manipulate the flow are in the IO package
There are two types of flow by operation data: byte stream and character stream
Flow is divided into: input stream, output stream.

(2)

Common base classes for IO streams
Abstract base class for byte stream
Inputstream,outputstream
Abstract base class for character streams
Reader,writer
The subclass names derived from these four classes are the suffixes of their parent class names as subclasses.

Two. Character Stream

1.FileWrite

The most common form of data is the file
FileWriter is a writer subclass object that is dedicated to manipulating files, without null argument constructors, because the object must be explicitly manipulated in order to initialize a cup. Also rice has a unique method, only inherited to the common method.
FileWriter (String fileName)

(1) Create a file and enter a certain content
The first step is to create a storage file
Filewritier fw=new FileWriter ("")//The IO exception needs to be handled here, can be thrown or try. Creates a file and the file is created in the specified directory. If the directory already has a file with the same name, it will be overwritten. This step is to clarify where the data is to be stored.
In the second step, the writer's write method is called, and the string is written to the stream
Fw.write ("");//The method also throws a memory exception
In the third step, the buffered data in the stream object is refreshed and the data is brushed into the destination file.
Fw.flush ();//will also throw an exception, and fw.close () can flush the stream, but it will close the stream resource and no longer operate on the convection to write to the data. It can only be used to free resources when the stream is no longer used.

The complete code is as follows

FileWriter FW =NULL;//External write stream reference, because if the word is written in a try statement, the object cannot be accessed in the finally statement. Try{FW=NewFileWriter ("Test.txt")///create stream and write method throws exception for exception handling Fw.write ("text");}Catch(IOException e) {System. out. println (E.tostring ());}finally{If (fw!=NULL)//must be judged here to prevent the stream from being created when it is not created successfully, the method cannot find the called objectTry{fw.close ();//will also throw exceptions for processing}Catch(IOException e) {System. out. println (E.tostring ()); }}

(2) Continue to write a file

FileWriter (String Filename,boolean append); Creates a stream through a constructor, when append is true, does not overwrite the existing file, and the data continues to be written at the end of the existing file. The other process is consistent with the previous steps.

2.FileReader

The stream reads data in two ways, one for single characters and one for reading in a character array.

(1)

The first step; FileReader fr=new FileReader ("");//Create a file to read the Liu object, and the file specified by the name associated with, and to ensure that the article is already exist, If no exception occurs, FileNotFoundException is a subclass of IOException.
The second step is Fr.read (); Returns an int representing an int object character, which needs to be cast to a char type, read only one character at a time, and read the next when read again. When the end of the stream is reached, 1 is returned. return int is not a byte type because when it happens to take 111111111 is also 1 can cause the program to stop, so promoted to int type, there are multiple bytes stored a byte, in front of 00000000111111111

The complete code is as follows

FileReader FR =NULL;Try{FR=NewFileReader ("C:\\Test.txt"); int ch=0;   while((Ch=fr.read ())!=-1) {System.out.prinln ("ch=" + (CHAR) ch);}}Catch(IOException e) {System. out. println ("read-exception:"+e.tostring ());}finally{if(fr!=NULL) {Try{fr.close (); }Catch(IOException e) {System. out. println ("close-exception:"+e.tostring ()); }
}
}

(2)

Read in a character array, not much different from the upper part of the code, the data container is changed

The code is as follows

FileReader FR =NULL;Try{FR=NewFileReader ("C:\\Test.txt"); Char[] buf =New Char[1024x768];//usually the array length is defined as an integer multiple of 1024. intlen=0;  while((Len=fr.read (BUF))!=-1) {System. out. println (NewString (BUF,0, Len));    /When the last line fails to fill the array contents, read part of the array. }}Catch(IOException e) {System. out. println ("read-exception:"+e.tostring ());}finally{    if(fr!=NULL){        Try{fr.close (); }        Catch(IOException e) {System. out. println ("close-exception:"+e.tostring ()); }
}
}

3. Buffer Technology

(1) BufferedWriter
Buffer of character stream
Improves the efficiency of reading and writing data, unlike previous reads
The buffer must be combined with a stream to be used, and the function is enhanced on the basis of the flow.
BufferedWriter (writer out); The constructor passes in the write stream as the actual argument, so there must be a stream object before the buffer is created, and this construction method creates a default-sized buffer character to write to the stream.

The first step is to create a write stream
FileWriter fw=new FileWriter ("");
The second step is to add buffering technology
BufferedWriter bufw=new BufferedWriter (FW);
The third step calls the Write method of BufferedWriter
Bufw.write ("");//Because the buffer bufferedwriter is a subclass of FileWriter, you can use methods inherited from the parent class. Remember to refresh the buffer stream as long as the buffer is used,
Bufw.flush ();
Bufw.close ();//Here the buffer is actually closed buffer stream object, so not in Fw.close ();

NewLine () Wrap, the unique method in the buffer is wrapped in the action, is a cross-platform line-wrapping method. To use when writing,

(2) Bufferreader

BufferedReader (reader R); In the constructor, the read stream is passed as the actual parameter.

The first step is to create a read stream object associated with the destination file
FileReader fr=new FileReader ("");
The second step creates the buffer, swapping the character read stream object as the actual parameter to the buffered object
BufferedReader bufr =new Bufferreader (FR);
The third step is to read the text data
The string line=null;//buffer provides a way to read one line at a time, ReadLine (), to facilitate the acquisition of text data, which is used to read the returned string type data, and to return NULL when there is no data, which can be used as a judgment condition to stop the read action
while ((Line=bufr.readline ())!=null) {
System.ou.println (line);//The data returned does not contain a terminator, so manual wrapping is required.
}
Bufr.close ();//the same buffer reads the closing of the object and closes the read stream.

Three. Byte stream

The operation is the same as the character stream, except that the character stream has a code table corresponding to the operation of the text, and the byte stream does not have a code table.

InputStream Read, OutputStream write
FileOutputStream fos=new FileOutputStream ("");
Fos.write ("". GetBytes ());//The Byte stream is not buffered when no buffer is specified, unlike a character stream that needs to buffer the bytes to look up the table for conversion to save and then refresh. But we still need to close the resources
Fos.close ();

Read operations are still available in both of the above ways. But there is a unique way to read
The available () method returns the total number of bytes that can be read, and then specifies an array of the corresponding size, one read and then output, without having to be read in a circular way by specifying the length of the array beforehand.
byte []buf=new byte[fis.available ()]//but only recommended when the size of the data is small, if too large may cause a memory overflow condition.
Fis.read (BUF);

Four. Other common stream objects

1. Reading the conversion stream improves efficiency.
A bridge of byte flow to a character stream
InputStreamReader (InputStream in)
The first step is to get the keyboard entry object
InputStream in=system.in;
The second step converts the obtained byte stream into a character stream object, using the transform flow
InputStreamReader isr=new InputStreamReader (in);
Step three to increase efficiency, add a character stream buffer count
Bufferreader bufr=new Bufferreader (ISR);
String Line=null;
while ((Line=bufr.readline ())!=null) {
if ("Over". Equals (line))
Break
System.out.println (Line.touppercase ());
}
Bufr.close ();

2. Write the conversion stream
Conversion of character stream into a bridge of byte
OutputStreamWriter (OutputStream out)

3. Standard input/output stream
Fields in the System class: In,out.
They represent system-standard input and output devices.
The default input device is the keyboard, and the output device is the monitor.
The type of system.in is InputStream.
The type of System.out is PrintStream Yes
Subclasses of the subclasses of the OutputStream class Filteroutputstream.

Example:

Get the keyboard input data and then flow the data to the display, then the monitor is the target
The ground.
The default device is changed by the Setin,setout method of the System class.
System.setin (New FileInputStream ("1.txt"));//change Source to file 1.txt.
System.setout (New FileOutputStream ("2.txt"));//Convert the purpose to file 2.txt
Because it is a byte stream processing is the text data, can be converted into a character stream, the operation is more convenient.
Bfferedreader BUFR =
New BufferedReader (New InputStreamReader (system.in));
BufferedWriter BUFW =
New BufferedWriter (New OutputStreamWriter (System.out));

4. Flow Operation rule
Through two clear to complete
The first clear source and purpose.
The second explicit operation data type.
The third is to specify which specific object to use.

Black Horse programmer _javaio Flow Overview

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.