Java:io stream of character streams reader, writer detailed

Source: Internet
Author: User

java.io in package: Character Streamtwo abstract base classes for a character stream:Reader Writerfile reads: Reader abstract class (in Java.io package)How to construct a direct subclass:filereader (file file)creates a new filereader given the File from which the data is read. FileReader (filedescriptor FD)creates a new filereader given the filedescriptor from which the data is read. FileReader (String fileName)creates a new filereader given the file name from which the data is read.  int read () reads a single characterNote: Characters that are read as integers, ranging from 0 to 65535 (0X00-0XFFFF), return 1 if the end of the stream has been reached .int Read (char[] cbuf) reads the characters into the array. Note: The number of characters read, or 1 if the end of the stream has been reached///Example 1: Read a single character using read () and output
ImportJava.io.*;classfilereaderdemo{ Public Static voidsop (Object obj) {System.out.print (obj); }     Public Static voidMain (string[] args)throwsIOException {//creates a file read stream object, associated with the file with the specified name. //Make sure that the file is already present. If it does not exist, an exception occurs, that is, FileNotFoundExceptionFileReader FR =NewFileReader ("F:\\myfile\\test.txt"); //invokes the Read method that reads the stream object. //the Read method reads the characters one time at a time and automatically reads the characters back.       intCH = 0;  while((Ch=fr.read ())!=-1) {SOP (Char) ch); }          /*while (true) {int ch = fr.read ();         if (ch==-1) break;  SOP ((char) ch); Read one of the characters in the file}*/Fr.close (); }}
///Example 2: Read characters into the array and output using Read (char[] cbuf)
ImportJava.io.*;classfilereaderdemo2{ Public Static voidsop (Object obj) {System.out.print (obj); }     Public Static voidMain (string[] args)throwsIOException {//creates a file read stream object, associated with the file with the specified name. //Make sure that the file is already present. If it does not exist, an exception occurs, that is, FileNotFoundExceptionFileReader FR =NewFileReader ("F:\\myfile\\test.txt"); //defines a character array for storing read characters      Char[] buf =New Char[1024]; intnum = 0;  while(num = Fr.read (BUF))!=-1)//num = fr.read (BUF) returns the number of characters read and returns 1 if the end of the stream has been reached .      {        //string (char[] value, int offset, int count) assigns a new string that contains the characters from a subarray of character array parameters. String str =NewString (buf,0, num);      SOP (STR);          } fr.close (); }}
then learn the character writing stream features: Writer abstract class (Java.io package)the FileWriter (file file) constructs a FileWriter object based on the given file object. since IO streams are used to manipulate data, the most common form of data is: Filethen the operation of the main file to display the first. requirement: On the hard disk, create a folder and write some text data. The suffix name is the parent class name, and the prefix name is the function of the stream object. found a writer subclass object specifically for manipulating files.  Public abstract void close ()throws IOException closes this stream, but refreshes it first. After you close the stream, calling write () or flush () will cause the IOException to be thrown. closing a previously closed stream is not valid. abstract void flush ()refreshes the buffer of the stream. ///Example 3:
ImportJava.io.*;classfilewriterdemo{ Public Static voidMain (string[] args)throwsIOException {//The first step://creates a FileWriter object that, when initialized, must have an explicitly manipulated file, and the file is created into the specified directory//If the directory already has a file with the same name, it will be overwritten. In fact, the step is to clear the destination of the data to be stored. FileWriter FW =NewFileWriter ("F:\\myfile\\demo.txt"); //Step Two://call the parent generic method write method, which writes the data to the stream. Fw.write ("asjdsjdfkskidkf,fdhjsdkjfdsk,dfhjdskj"); //Step Three://call the parent generic method flush method, flush the data in the buffer in the stream object, and flush the data to the destination. Fw.flush (); //you can then write data to the destinationFw.write ("Xiayuanquan");                Fw.flush (); //the common method in the parent class Close method closes the stream resource, but refreshes the data in the internal buffer once before closing, flushing the data to the destination. //difference from flush: After flush refreshes, the stream can continue to be used, and when close refreshes, the stream is closed and cannot continue to be used. Fw.write ("Aaaaaaaaaaaaaa"); Fw.close (); //Stream closed//fw.write ("xxxx");//The stream is closed and no more data can be written to the destination file at this time            }}
when you use a character stream to read and write data, you may get a stream exception, such as a file does not exist, a path error, and so on, we need to capture and process the exception. ///Example 4:
ImportJava.io.*;classfilewriterexceptiondemo{ Public Static voidMain (string[] args) {FileWriter fw=NULL; Try{FW=NewFileWriter ("F:\\myfile\\exception.txt");//Create a target fileFw.write ("My name is xiayuanquan!");//Write data content into the stream        }        Catch(IOException IE) {System.out.println (ie.tostring ()); }        finally        {            Try            {              if(fw!=NULL) Fw.close (); //refreshes the stream, brushes the data content in the stream to the destination file, and then closes the stream resource            }            Catch(IOException IE) {System.out.println (ie.tostring ()); }        }    }}
Expand: When the user wants to write data to the same file, but the content already exists in the file, then the newly written data will replace the previous data. At this point, this is not what the user wants, and in this case, we can write the newly written content after the contents of the file. A method is provided in the API as follows:continuation of the contents of the existing file data:FileWriter (File File, Boolean append)constructs a FileWriter object based on the given File object. ///Example 5:
ImportJava.io.*;classfilewriterdemoappend{ Public Static voidMain (string[] args) {FileWriter fw=NULL; Try        {            //pass a ture parameter, which means that the existing file is not overwritten. And the continuation of the document at the end of the existing document. FW =NewFileWriter ("F:\\myfile\\demo.txt",true); Fw.write (",,, Wei-zhong-hua-jue-qi-er-du-shu"); Fw.write ("\r\nabc=abc");//' \ r \ n ' means line break, then continue writing data        }        Catch(IOException e) {System.out.println (e.tostring ()); }        finally        {            Try            {                if(fw!=NULL) Fw.close (); }            Catch(IOException e) {System.out.println (e.tostring ()); }        }    }}
Comprehensive Exercise: Assign the next text file in the same directory to another text file. (example: F:\\myfile\\practice.txt--------->f:\\myfile\\test.txt)idea: The first step is to create a read stream associated with the f:\\myfile\\practice.txt. The second step is to read all the data in the f:\\myfile\\practice.txt into the stream and place it inside the defined array, and then close the resource. Third, create a write stream associated with F:\\myfile\\test.txt, and set the Resume function to True for the Boolean value;Fourth, write the data contents of the array defined in the second section to the F:\\myfile\\test.txt file, and then close the resource. ///Example 6:
ImportJava.io.*;classcopytext{ Public Static voidMain (string[] args)throwsIOException {FileReader fr=NewFileReader ("F:\\myfile\\practice.txt"); FileWriter FW=NewFileWriter ("F:\\myfile\\test.txt",true); //The first way: (after all the data is read into the buffer, and then one time to continue to write to the target file)        intNum=0; Char[] buf =New Char[1024];  while(num = Fr.read (buf))!=-1) {String str=NewString (buf,0, num); Fw.write ("\ r \ n" +str); //Fw.write (buf,0,num);Fw.close ();                } fr.close (); /*///second method: (writes a data to the target file each time a data is read) int num = 0;        while (num = Fr.read ())!=-1) {fw.write (num);        } fw.write ("\ r \ n");        Fw.close ();        Fr.close (); */    }}

 

Java:io stream of character streams reader, writer detailed

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.