Java IO learning notes (1), javaio learning notes

Source: Internet
Author: User

Java IO learning notes (1), javaio learning notes
Basic knowledge 1. stream classification all streams are in java. io packages are divided by stream direction: input stream and output stream are divided by Data Processing Unit: byte stream and worker stream according to different functions: node stream and abstract class of various stream processing, all streams inherit from these four streams.

  Byte stream Ghost stream
Input stream InputStream Reader
Output stream OutputStream Writer
Note: Write is to write outside the program, with the output stream; read is to read in the program, with the input stream; input stream and output stream are from the perspective of the program for the byte stream: read in the original format. The read results are 0 and 1 strings, but one byte and one byte (eight bits and eight bits. Streams are read by a single character (one character is 2 bytes and 16 characters. Node stream: directly connects to the data source and reads and writes data (such as files and memory) from the data source to process the stream: used to process the node stream, connected to existing streams (including node streams and processing streams), it is used to process streaming data and provides more powerful read/write functions for programs. A stream can be used to process multiple layers of streams. 2. The basic method of InputStream inherited from InputStream is used to input data to the program. The unit of data is byte (8 bits), and the middle and depth are byte streams, the light color is the processing stream.

 

(1) int read () throws IOException: reads a byte and returns the result in an INTEGER (0-255 ), the Return Value of the method is supervised. If-1 is returned, it indicates that the input stream has been read to the end. (2) int read (byte [] buffer) throws IOException: read a byte and store it in an array buffer. The byte is compared to a water drop. The stream is water flow, and the buffer is equivalent to a bucket, this method is equivalent to storing a drop of water in a bucket after receiving it, and processing the read data (filled with buckets) after reading buffer bytes ), int returns the number of actually read bytes and the number of actually read bytes. If the number of bytes has reached the end of the input stream before reading, return-1. (3) int read (byte [] buffer, int offset, int length) throws IOException, read length bytes coexist in the byte array buffer, starting from the buffer offset position, the returned value is the number of bytes actually read. The returned int value can be smaller than the length value. (4) void close () throws IOException close the stream to release memory resources. (5) the number of bytes skipped by the long skip (long n) throws IOException is not read. 3. The basic method of outputStream inherits from the stream of outputStream. It is used to output data in the program, and the unit of data is byte. The middle color is byte stream, and the light color is the processing stream (1) void write (int B) throws IOException; write a byte data to the output stream, which is the 8-bit low of parameter B. (2) void write (byte [] B) throws IOException; write data from a byte array to the output stream. (3) void write (byte [] B, int off, int len) throws IOException; writes The len bytes in a byte array starting from the specified off to the output stream. (4) void close () throws IOException; close the stream to release memory resources (5) void flush () throws IOException; important: when the close () method is used to close the output stream, it is possible that the data has not been completely written to the output stream, and the output stream is roughly closed. Therefore, we must develop a good habit in IO programming. Before closing the output stream, we must call flush () method to write all the data in the output stream buffer to the destination. According to the help documentation, although there is a flush Method for outputStream and the flush method is usually written for programming, it does not work for outputStream and its subclass. 4. The basic method of Reader inherits from the stream of Reader, which is used to input data into the program. The difference with InputStream is that the unit of data is character (16 bit ), for example, when processing Chinese characters, Chinese characters occupy two bytes. If byte streams are used, it is possible that half of Chinese characters are read. Therefore, it is necessary to merge streams. The middle and dark colors are the node streams, and the light colors are the processing streams.

 

5. The basic method of Writer inherits from the stream of writer, which is used to input data into the program. The difference with outputStream is that the unit of data is character (16 bit ), for example, when processing Chinese characters, Chinese characters occupy two bytes. If byte streams are used, it is possible that half of Chinese characters are written. Therefore, it is necessary to merge streams. The middle and dark colors are the node streams, and the light colors are the processing streams. Here, the void write (String string) method writes the characters in a String to the output stream. The implementation process is to call java. lang. the toCharArray () method of String converts the String into a character array and writes it to the output stream. Void write (String string, int offset, int length) throws IOException starts from the offset position of the String and writes the length to the output stream. 5. sub-classes of the stream and their basic methods (1) File Processing FileInputStream and FileOutputStream: these are inherited from InputStream and OutputStream, respectively, used to input and output bytes to the file. Common constructor: FileInputStream is used to read the original bytes of data from a file. For example, to read an image, use FileReaderFileInputStream (String name) to read character-type data) throws FileNotFoundException creates a file input stream and connects to all files named name in the system. FileInputStream (File file) throws FileNotFoundException creates a File input stream and connects to the specified file. FileOutputStream (String name) throws FileNotFoundException creates a file output stream and writes the output data to the file with the specified name. FileOutputStream (File file) throws FileNotFoundException creates a File output stream and writes the data to the specified file. FileOutputStream automatically creates a file when the file does not exist, but does not automatically create a path that does not exist. If the path does not exist, the file does not exist, and cannot be created, but the file does not exist but cannot be opened, a FileNotFoundException exception will be thrown. FileOutputStream (String name, boolean append) throws FileNotFoundExceptionFileOutputStream (File file, boolean append) throws FileNotFoundExceptionFileInputStream and FileOutputStream support all read/write methods provided by InputStream and OutputStream. Note: when instantiating FileInputStream and FileOutputStream streams, you must use try... the catch statement is used to handle FileNotFoundException that may be thrown. You must use try when calling the read/write method... the catch statement is used to handle IOException that may be thrown. FileNotFoundException is a subclass of IOException. Exercise applet I: Use a byte input stream to read the package test content in the file. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. IOException; public class FileInputStreamTest {public static void main (String args []) {FileInputStream fin = null; int B = 0; try {// The path "\". If you directly use the Backslash "\", an error is returned, here we need to use two Backslash "\" or a forward slash "/" fin = new FileInputStream ("E: \ technical learning \ java \ test \ Socket \ test.txt ");} catch (FileNotFoundExceptio N e) {e. printStackTrace (); // print the error message to the console. If you do not write it, the error message will not be printed on the console. System. out. println ("file does not exist");} try {while (B = fin. read ())! =-1) {// System. out. print (B); System. out. print (char) B);} fin. close ();} catch (IOException e) {e. printStackTrace (); System. out. println ("file read error ");}}} If you use fileInputStream. read () is garbled when reading Chinese characters. Because fileInputStream is a byte stream, only one byte can read content in one byte. Each Chinese Character occupies two bytes, and half Chinese characters are read, not identified, so garbled.Note: A strange error occurs during the exercise: int B = 0 in the program during the exercise; this line does not exist. The Code in the following try block is: while (fin. read ()! =-1) {System. out. print (char) fin. read ();} will get a strange result: the console only prints the content at the double number. For example, input the 26 English letters abcdefghijklmnopqrstuvwxyz and print the result: bdfhjlnprtvxz. This is because every execution of fileInputStream. the read () method reads the content of a byte and executes a fin in the while condition. read (), the read result is to judge whether the print is not made, and the System in. out. print (char) fin. read (); execute the read method again to read the content of the next byte. Therefore, the output is the content of the next byte, And the bytes at the singular position are empty. Exercise applet 2: copy the file content PackageTest. io. file; ImportJava. io. FileInputStream; ImportJava. io. FileNotFoundException; ImportJava. io. FileOutputStream; ImportJava. io. IOException; Public ClassFileOutputStreamTest { Public Static VoidMain (String args []) {FileOutputStream fos = Null; FileInputStream FCM = Null; IntB = 0; Try{Fiis = NewFileInputStream ("E:/technology learning/java/test/Socket/TalkClient. java"); fos = NewFileOutputStream ("E:/technology learning/java/test/Socket/testtest.txt ");} Catch(FileNotFoundException e) {e. printStackTrace (); System. Out. Println ("the file does not exist or the file cannot be opened ");} Try{ While(B = FCM. read ())! =-1) {fos. write (B);} fos. flush (); FCM. close (); fos. close (); System. Out. Println ("file copied ");} Catch(IOException e) {e. printStackTrace (); System. Out. Println ("file read/write error") ;}} exercise applet 3: reading a file through the ghost stream PackageTest. io. file; ImportJava. io. FileNotFoundException; ImportJava. io. FileReader; ImportJava. io. IOException; Public ClassFileReaderTest { Public Static VoidMain (String [] agrs) {FileReader fr = Null; IntB = 0; Try{Fr = NewFileReader ("E:/technology learning/java/test/Socket/TalkClient. java ");} Catch(FileNotFoundException e) {e. printStackTrace (); System. Out. Println ("file does not exist ");} Try{ While(B = fr. read ())! =-1) {System. Out. Print (( Char) B);} fr. close ();} Catch(IOException e) {e. printStackTrace (); System. Out. Println ("file read error") ;}} exercise applet 4: writable stream file writing PackageTest. io. file; ImportJava. io. FileWriter; ImportJava. io. IOException; Public ClassFileWriterTest { Public Static VoidMain (String args []) {FileWriter fw = Null; Try{Fw = NewFileWriter ("E:/technology learning/java/test/Socket/test1.txt ");} Catch(IOException e) {e. printStackTrace ();} Try{ For( IntI = 0; I <5000; I ++) {fw. write (I);} fw. flush (); fw. close (); System. Out. Println ("file content written successfully ");} Catch(IOException e) {e. printStackTrace ();}}}

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.