1. Batch stream
In the program, a character is equal to two bytes. Java provides two classes for the reader and writer to operate the volume stream.
1) character output stream: writer
Writer is an abstract class, so to use it, you must instantiate it through its subclass before using it.
Common method of writer class
Method Name |
Description |
Public abstract void close () throws ioexception |
Close output stream |
Public void write (string Str) throws ioexception |
Output string |
Public void write (char cbuf) throws ioexception |
Output character array |
Public abstract void flush () throws ioexception |
Forcibly clear Cache |
Example 1: helloworld
Write data to a text file using the character output stream
Public static void main (string [] ARGs) throws exception {// declare a file object file = new file ("hellowolrd.txt "); // declare a write object writer = NULL; // use the filewriter class to instantiate the writer Class Object and write it as an append to writer = new filewriter (file, true ); // declare a string STR = "writing to helloworld in string form"; // write to writer in text file. write (STR); // refresh writer. flush (); // close the character output stream writer. close ();}
2) character input stream: Reader
Reader itself is also an abstract class. If you use it, you need to instantiate it through its subclass to use it.
Common Methods of reader class
Method Name |
Description |
Public abstract void close () throws ioexception |
|
Public int read () throws ioexception |
|
Public int read (char cbuf) throws ioexception |
|
The reader class provides only one method for reading characters.
Example 2: helloworld
Read the content in the text and display it on the console.
Public static void main (string [] ARGs) throws exception {// declare a file object file = new file ("hellowolrd.txt "); // declare a reader Class Object reader = NULL; // instantiate the reader object reader = new filereader (File) through the filereader subclass ); // declare a character array char [] C = new char [1024]; // output the content // int Len = reader. read (c); // The loop mode reads int Len = 0 one by one; int temp = 0; while (temp = reader. read ())! =-1) {C [Len] = (char) temp; Len ++;} // close the input stream reader. close (); // convert the char array to a string and output the system. out. println (new string (C, 0, Len ));}
2. Differences between the byte stream and the byte stream
When operating byte stream operations, the buffer zone is not used, but the file itself is directly operated, while the byte stream uses the buffer zone during operations.
If we do not close the stream when operating the primary stream, the data we write cannot be saved. Therefore, you must remember to close the stream when operating the livestream.