Dark Horse programmer--java Base---IO (input output) stream character streams

Source: Internet
Author: User

Dark Horse programmer--java Base---IO (input output) stream character streams

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

IO (Input Output) Flow features:

1,io streams are used to process data transfers between

2,java the operation of the data is through the flow of the way;

3,java the objects used to manipulate the flow are in the IO package;

4, flow according to operational data are divided into two types: byte stream and character stream;

5, Flow is divided into: input stream and output stream by flow direction.

Note: A stream can manipulate only data, not files.

3.common base classes for IO streams:

1) abstract base stream for byte stream:InputStream and outputstream

2) abstract base stream of character streams:reader and Writer

Note: The subclass names derived from this four class are suffixes with the name of the parent class as the subclass name, the prefix is its function, such as the InputStream subclass FileInputStream;Reader Subclass FileReader

Since IO streams are used to manipulate data, the most common form of data is: files.

Requirement: On the hard disk, create a file and write some text data.

Found a writer subclass object specifically for manipulating files. FileWriter. The suffix name is the parent class name, and the prefix name is the function of the stream object.

The following example:

ImportJava.io.*;classfilewriterdemo{ Public Static voidMain (string[] args)throwsIOException {//creates a FileWriter object.        When the object is initialized, it must explicitly manipulate the 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. //in fact, the step is to specify the destination of the data to be stored. FileWriter FW =NewFileWriter ("Demo.txt"); //call the Write method to write the string to the stream. Fw.write ("ABCDE"); //refreshes the data in the buffer in the Stream object. //brushes the data to the destination. //Fw.flush (); //The stream resource is closed, but the data in the internal buffer is refreshed once before it is closed. //brushes the data to the destination. //and flush difference: After flush refreshes, the stream can continue to be used, and when close is refreshed, the stream is closed. Fw.close (); }}

Attention:

In fact, Java itself can not write data, but to call the system internal way to complete the writing of data, using system resources, it is important to close the resources.

Close () and flush () differences:

Flush () After flushing, the stream can continue to be used;

When close () is refreshed, the stream is closed and the character stream is no longer written.

2, How to handle IO exception

Because you need to specify the Create file location when you create the object, the IOException exception occurs if the specified location does not exist, so you need to try processing the IO exception throughout the step.

/*how the IO exception is handled. */ImportJava.io.*;classfilewriterdemo2{ Public Static voidMain (string[] args) {FileWriter fw=NULL; Try{FW=NewFileWriter ("Demo.txt"); Fw.write ("ABCDEFG"); }        Catch(IOException e) {System.out.println ("Catch:" +e.tostring ()); }        finally        {            Try            {                if(fw!=NULL) Fw.close (); }            Catch(IOException e) {System.out.println (e.tostring ()); }        }            }}

Attention:

1, define the file path, you can use "/" or "\ \".

2, when creating a file, if the directory has the same name file will be overwritten.

3, when reading a file, you must ensure that the file already exists, otherwise out of the ordinary.

4, when the flow is closed, to determine whether the flow is empty;

Continue to write data for existing files

The continuation of the data of the file is through the constructor FileWriter (Strings,boolean append), when the object is created, passing a true parameter, which means that the existing file is not overwritten. And the data is resumed at the end of the existing document. (a line break in a file in a Windows system is represented by \ r \ n Two escape characters, and only \ n is used in the Linux system for line breaks), as follows:

/*demonstrates the continuation of data for an existing file. */ImportJava.io.*;classfilewriterdemo3{ Public Static voidMain (string[] args) {FileWriter fw=NULL; Try        {//pass a true parameter, which means that the existing file is not overwritten. And the data is resumed at the end of the existing document. FW =NewFileWriter ("Demo.txt",true); Fw.write ("Nihao\r\nxiexie"); }        Catch(IOException e) {System.out.println ("Catch:" +e.tostring ()); }        finally        {            Try            {                if(fw!=NULL) Fw.close (); }            Catch(IOException e) {System.out.println (e.tostring ()); }        }            }}

File stream Read

There are two ways to read a file: The first is to read a single character, and the second is to read it through a character array.

1, read one character at a time:

ImportJava.io.*;classfilereaderdemo{ Public Static voidMain (string[] args)throwsIOException {//creates a file that reads the stream object, and associates the file with the specified name. //to ensure that the file is already present, an exception will occur if it does not exist FileNotFoundExceptionFileReader FR =NewFileReader ("Demo.txt"); //invokes the Read method that reads the stream object. //Read (): read one character at a time. and will automatically read down.                 intCH = 0;  while((Ch=fr.read ())!=-1) {System.out.println (CH); }        /*while (true) {int ch = fr.read ();            if (ch==-1) break;        System.out.println ("ch=" + (char) ch); }        */        //Close Streaming ResourcesFr.close (); }}

2, read by a character array

/*The second way: Read through a character array. */ImportJava.io.*;classFileReaderDemo2 { Public Static voidMain (string[] args) {FileReader fr=NULL; try{FR=NewFileReader ("Demo.txt"); //defines a character array.            Used to store read-to characters. //the Read (char[]) returns the number of characters.             Char[] buf =New Char[1024]; intnum = 0;  while((Num=fr.read (BUF))!=-1) {System.out.println (NewString (buf,0, num)); }        }Catch(Exception e) {System.out.println (e); }        finally{            if(FR! =NULL){                Try{fr.close (); }                Catch(IOException e) {}}} }}
Small exercise: Copy the text file, copy the C-drive text file to the D drive.
ImportJava.io.FileReader;ImportJava.io.FileWriter;Importjava.io.IOException;/*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. */ Public classCopyText { Public Static voidMain (string[] args) {//TODO auto-generated Method Stubcopy_2 (); }    //read a character array from the C drive before writing to the D disk     Public Static voidcopy_2 () {FileWriter FW=NULL; FileReader FR=NULL; Try{FW=NewFileWriter ("C:\\a.txt"); Fr=NewFileReader ("D:\\b.txt"); Char[] buf =New Char[1024]; intLen = 0;  while((Len=fr.read (BUF))!=-1) {fw.write (buf,0, Len); }        }        Catch(IOException e) {Throw NewRuntimeException ("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 voidcopy_1 () {//Create a destination. FileWriter FW =NULL; FileReader FR=NULL; Try{FW=NewFileWriter ("C:\\a.txt"); //associated with an existing file. FR =NewFileReader ("D:\\b.java"); intCH = 0;  while((Ch=fr.read ())!=-1) {fw.write (CH); }        } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }finally{            if(FW! =NULL){                Try{fw.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }            if(FR! =NULL){                Try{fr.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }        }    }}

Dark Horse programmer--java Base---IO (input output) stream character streams

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.