IO streams are used to process data transmission between devices.
Java operates data through a stream.
Java objects used for stream operations are all in the IO package.
Streams are divided into byte streams and byte streams.
Streams are divided into input streams and output streams by flow.
I. History stream:
Previously, the data was processed in bytes. You can use byte stream technology.
Because of the continuous appearance of later encoding tables, the code table for recognizing a specific text is not unique. Such as Chinese, GBK, and unicode.
The encoding problem occurs.
Chinese byte data gbk --> stream processing ---> gbk resolution is acceptable.
Later Stage: The container encountered the following problems:
Chinese byte data gbk --> stream processing unicode to process --> data errors.
To process text data, you need to combine byte stream technology with the encoding table. Note: Only the text is like this, because the text involves encoding.
This issue is not involved in other data, such as dvd mp3 images.
Although the byte stream + encoding table can solve the problem of text data processing, it is more troublesome.
For ease of use, the byte stream and the encoding table are encapsulated, and a stream technology that is convenient for text operations is introduced: the byte stream.
In fact, the bytes stream is: byte stream + encoding table.
Ii. IO System
Two base classes of byte stream:
InputStream (byte input stream) OutputStream (byte output stream)
The primary stream has two base classes:
Reader (character input stream) Writer (character output stream)
Learn the io stream system: view the top layer (parent class features) and use the bottom layer (subclass objects ).
One benefit of this system is:
The suffix name of each subclass is the name of the parent class of the system, and it is easy to distinguish the system. In addition, each subclass prefix name represents the function of this subclass object.
Iii. Exercises
1. Requirement: Write a text segment to the hard disk.
Ideas:
1. A piece of text is string data.
2. Writing string data to the hard disk is stored in the memory, and the data in the memory is written to the hard disk, which involves data processing between devices. I/O technology is required. From memory to hard disk, it should be the output stream.
3. For text, io provides convenient operations, such as a text stream.
4. In combination with the two, the output stream is required, and the character output stream is required. Writer
5. Which subclass object is used? A file is used to store data on a hard disk. In the Writer system, you want to know the Writer objects that can operate files.
The specific object FileWriter is found.
1. Use FileWriter to create a stream object. During construction, you must specify the location where the data to be written needs to be stored.
When this object is created, the target file is created.
If the file already exists, it will be overwritten.
What have you done? Create an object in heap memory. System resources are also called.
FileWriter fw = new FileWriter ("demo.txt ");
Create the demo.txt file under the current directory.
2. Use the character output stream object to write the string. Call the write method.
Data is not directly written to the target file, but to the temporary buffer.
Fw. write ("abcdef ");
3. How can we get the data into a file? The Writer class has a flush () method. Refresh the buffer and immediately write the buffered data to the target.
Fw. flush ();
4. Close the stream and close the resource. Before disabling the service, you must first buffer the data and write the data to the destination.
Fw. close ();
Fw. write ("XIXI"); // The Stream closed has been disabled. No more
What is the difference between flush () and close?
Flush (): only refreshes the data in the buffer to the destination. Stream objects can be used. It can be used multiple times.
Close (): After the data in the buffer is flushed to the destination, the stream resource is directly closed, and the stream cannot continue to be used. It can be used only once.
In the close () method, a flush () is called before it is closed ();
2. Requirement: You want to continue writing.
This object cannot be created because the existing files are overwritten when the structure is created.
You can use another constructor to add a boolean parameter, which is true to implement continued writing.
3. Requirement: You want to write data into a data branch.
Special software in window, such as notepad. Only special line breaks \ r \ n in the window are identified.
To wrap lines on different system platforms. You can use the System class to obtain information about the current System.
Code for continued writing and line feed:
Private static final String LINE_SPARATOR = System. getProperty ("line. separator ");
Public static void main (String [] args) throws IOException {
FileWriter fw = new FileWriter ("tempfile \ demo2.txt", true );
Fw. write ("xi" + LINE_SPARATOR + "xi ");
Fw. close ();
}
Iv. IO Exception Handling specifications
IO Exception Handling specification: Create a stream object. Create a stream object reference outside the try. Initialize the streaming object in try.
FileWriter fw = null;
Try {
Fw = new FileWriter ("k: \ demo3.txt ");
Fw. write ("abcde ");
Fw. flush ();
} Catch (IOException e ){
System. out. println (e. toString ());
} Finally {
If (fw! = Null) robustness. Otherwise, a null pointer exception occurs. Note: If you need to disable multiple streams, You need to judge them one by one.
Try {
Fw. close ();
} Catch (IOException e ){
Related code processing. For example, you can record the failed information to the log file.
Throw new RuntimeException ("failed to close ");
}
}
5. read characters from FileReader
Public static void main (String [] args) throws IOException {
Use FileReader to specify the file to be read during construction.
Use FileReader to associate with the specified file.
FileReader fr = new FileReader ("tempfile \ demo.txt ");
Call the read method of the character reading Stream object. Read the associated files.
Read (): read one character at a time. Returns the number corresponding to the character.
If you read any character, the system returns the character. If you read the character at the end, the system returns-1. The end is indicated by-1.
// Int ch = fr. read ();
// System. out. println ("ch =" + ch );
// Int bytes = fr. read ();
// System. out. println ("response =" + response );
// Int ch2 = fr. read ();
// System. out. println ("ch2 =" + ch2 );
// Int ch3 = fr. read ();
// System. out. println ("ch3 =" + ch3 );
// The code is cyclically resolved.
Int ch = 0;
While (ch = fr. read ())! =-1 ){
System. out. println (char) ch );
}
// Close the resource.
Fr. close ();
}
Method 2 for FileReader to read characters
Requirement: demonstrate the read (char []); read method in Reader. This reading efficiency is much higher than the first one.
FileReader fr = new FileReader ("tempfile \ demo.txt ");
// Create a character array.
Char [] buf = new char [1024];
// The read (char []) method in Reader is called.
// Store the read characters in the array and return the number of read characters.
// Int len1 = fr. read (buf );
// System. out. println (len1 + ":" + new String (buf, 0, len1 ));
// Int len2 = fr. read (buf );
// System. out. println (len2 + ":" + new String (buf, 0, len2 ));
// Int len3 = fr. read (buf );
// System. out. println (len3 + ":" + new String (buf, 0, len3 ));
// Int len4 = fr. read (buf );
// System. out. println (len4 + ":" + new String (buf ));
Cycle
Int len = 0;
While (len = fr. read (buf ))! =-1 ){
System. out. println (new String (buf, 0, len ));
}
Fr. close ();
}
6. Copy a text file
Exercise: copy a text file on drive C to drive D.
Ideas:
1. The C drive file is a data source.
The copied disk D indicates that the disk D is the purpose of data storage. This object should contain a file.
2. Read the files on drive C first. Write the read data to the destination.
3. Since it is an operation text file, you only need to use the response stream.
Method 1: Low Efficiency for reading and writing
Public static void main (String [] args) throws IOException {
// 1. Create a character to read the stream object and associate it with the source.
FileReader fr = new FileReader ("tempfile \ iostream .txt ");
// 2. Create a character output stream object to specify the purpose of data storage.
FileWriter fw = new FileWriter ("tempfile \ copy_demo.txt ");
// 3. Perform read/write operations. Read one and write one.
Int ch = 0;
While (ch = fr. read ())! =-1 ){
Fw. write (ch );
}
// 4. Close the resource.
Fw. close ();
Fr. close ();
}
Method 2: first store the source file data on the hard disk to the cache area created in the memory through the input stream, and then write the data from the cache area to the target file through the output stream. High Efficiency
Use a buffer array.
The read and write methods of arrays can be operated.
// 1. Define the reference of the character input stream and the character output stream.
FileReader fr = null;
FileWriter fw = null;
Try {
// 2. initialize the streaming object.
Fr = new FileReader ("tempfile \ demo.txt ");
Fw = new FileWriter ("tempfile \ copy_demo2.txt ");
// 3. Define an array buffer. Used to buffer read data.
Char [] buf = new char [1024];
// 4. read/write operations.
Int len = 0;
While (len = fr. read (buf ))! =-1 ){
Fw. write (buf, 0, len); read len, write len characters
}
} Catch (Exception e ){
System. out. println (e. toString ());
} Finally {
If (fw! = Null)
Try {
Fw. close ();
} Catch (IOException e ){
Throw new RuntimeException ("Write close failed ");
}
If (fr! = Null)
Try {
Fr. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
7. string buffer. BufferedWriter
The buffer zone improves the efficiency of stream operation (read/write). Therefore, the object in the buffer zone must have a stream object.
Public static void main (String [] args) throws IOException {
// Create a stream object.
FileWriter fw = new FileWriter ("tempfile \ buf.txt ");
// To improve efficiency. Create a buffer object and associate it with the stream to improve efficiency.
BufferedWriter bufw = new BufferedWriter (fw );
// Use the buffer method. Because the buffer operations are efficient methods of elements in the array.
Bufw. write ("abcde ");
Bufw. newLine (); line feed = System. getProperty ("line. separator ");
Bufw. write ("xixixi ");
// Refresh the buffer. Remember: Generally, you only need to refresh the buffer.
Bufw. flush ();
// Disable the buffer.
Bufw. close (); // Q: Disable fw. close ()? No, because the buffer is closed, the stream associated with the buffer is actually closed.
}
8. String Buffer BufferedReader
Demonstrate BufferedReader
1. Read the stream with characters first.
2. This class has a special method. ReadLine (). Read a row at a time.
// Create a stream reading object and associate it with a file.
FileReader fr = new FileReader ("tempfile \ buf.txt ");
// Create an association between the read buffer object and the stream object to perform efficient operations on the object.
BufferedReader bufr = new BufferedReader (fr );
// String line1 = bufr. readLine ();
// System. out. println ("line1:" + line1 );
// String line2 = bufr. readLine ();
// System. out. println ("line2:" + line2 );
// String line3 = bufr. readLine ();
// System. out. println ("line3:" + line3 );
// String line4 = bufr. readLine ();
// System. out. println ("line4:" + line4 );
// String line5 = bufr. readLine ();
// System. out. println ("line5:" + line5 );
String line = null;
While (line = bufr. readLine ())! = Null ){
System. out. print (line );
}
Bufr. close ();
}
9. Use a buffer to copy text files. This buffer can only be used for text files.
BufferedReader bufr = null;
BufferedWriter bufw = null;
Try {
Bufr = new BufferedReader (new FileReader ("tempfile \ iostream .txt "));
Bufw = new BufferedWriter (new FileWriter ("tempfile \ copy_buf.txt "));
// Read and write rows.
String line = null;
While (line = bufr. readLine ())! = Null ){
Bufw. write (line );
Bufw. newLine ();
Bufw. flush ();
}
Catch (Exception e ){
System. out. println (e. toString ());
} Finally {
If (bufw! = Null)
Try {
Bufw. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
If (bufr! = Null)
Try {
Bufr. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}