1, Overview
1. Introduction
I/O is the abbreviation of Input/Output. IO stream is used to process data transmission between devices, such as reading / writing files, network communication, etc. Java operates on data through stream. java. Various "stream" classes and interfaces are provided under the IO package to obtain different kinds of data and input or output data through standard methods.
input: read external data (data from disk, optical disc and other storage devices) into the program (memory).
Output: output program (memory) data to disk, optical disc and other storage devices.
2. Classification
According to different operation data units, it is divided into byte stream (8 bit) and character stream (16 bit).
According to the flow direction of data flow, it is divided into input flow and output flow.
According to the different roles of the flow, it is divided into node flow (file flow) and processing flow.
Node flow (file flow): it directly acts on the file to read and write data from the data source or destination.
Processing flow: it does not directly act on the file or connect to the data source or destination, but "connect" to the existing flow (node flow or processing flow) to provide more powerful reading and writing functions for the program through data processing.
Node flow:
Process flow:
3. IO stream system
Four top-level abstract base classes.
The names of subclasses derived from these four classes are suffixed by their parent classes. Example: subclass FileInputStream of InputStream, subclass FileReader of Reader.
The system of IO flow is as follows: focus on the highlighted part.
[access file] is a node stream (file stream), and others (except abstract base classes) are processing streams.
2, Character stream
1. FileReader (input)
Convenient class for reading character files. The construction method of this class assumes that both the default character encoding and the default byte buffer size are appropriate. To specify these values yourself, you can first construct an InputStream on the FileInputStream.
read(): read one character at a time, and the pointer will point to the next character. Returns - 1 at the end of the read.
Code example: reading files
1 // File: F:\\hello.txt 2 // Content: helloworld123 Chinese 1 3 public class Main { 4 public static void main(String[] args) { 5 try (FileReader fr = new FileReader(new File("F:\\hello.txt"));) { 6 int data; 7 while ((data = fr.read()) != -1) { 8 System.out.print((char) data); 9 } 10 } catch (Exception e) { 11 } 12 } 13 } 14 15 // result 16 helloworld123 Chinese
read(char[] buff): read buff once Length characters, return the number of read. Returns - 1 at the end of the read.
Code example: wrong writing
1 // File: F:\\hello.txt 2 // Content: helloworld123 Chinese 1 3 public class Main { 4 public static void main(String[] args) { 5 try (FileReader fr = new FileReader(new File("F:\\hello.txt"));) { 6 char[] buff = new char[5]; 7 int len; 8 9 while ((len = fr.read(buff)) != -1) { 10 // Mode 1: 11 for (char c : buff) { 12 System.out.print(c); 13 } 14 15 // Mode 2: 16 // String str = new String(buff); 17 // System.out.print(str); 18 } 19 } catch (Exception e) { 20 } 21 } 22 } 23 24 // result.Both mode 1 and mode 2 are 25 helloworld123 Chinese 13 China
Code example: correct writing
1 // File: F:\\hello.txt 2 // Content: helloworld123 Chinese 1 3 public class Main { 4 public static void main(String[] args) { 5 try (FileReader fr = new FileReader(new File("F:\\hello.txt"));) { 6 char[] buff = new char[5]; 7 int len; 8 9 while ((len = fr.read(buff)) != -1) { 10 // Mode 1: 11 for (int i = 0; i < len; i++) { 12 System.out.print(buff[i]); 13 } 14 15 // Mode 2: from buff The subscript 0 of starts to take characters, and takes len individual 16 // String str = new String(buff, 0, len); 17 // System.out.print(str); 18 } 19 } catch (Exception e) { 20 } 21 } 22 } 23 24 // result 25 helloworld123 Chinese 1
Deeply understand the read(char[] buff) method: read buff at one time Length characters, print. When reading the next time, the last read character is still in the character array, so the last "person 1" only covers the first two characters of the last time, so that the last character array is "person 1 3 China".
2. FileWriter (output)
The construction method must specify the file to be operated. If it does not exist in the specified directory, it will be created; If it exists, it will be overwritten. Relevant API s are as follows:
new FileWriter(String fileName): creates a file in the specified directory
new FileWirter(String fileName, boolean append): whether to append data
void write(String int): overload to write the string to the stream
void write(char[] buff): writes a character array
void wirte(char[] buff, int off, int len): writes a part of the character array
void flush(): refresh the stream. The stream can continue to be used
void close(): brush the new stream first and close the stream. The stream cannot continue to be used
Note: write to newline through write() \ r\n, and the corresponding bytes are 13 and 10
Code example: writing files
1 public class Main { 2 public static void main(String[] args) { 3 // The default is not to append and overwrite the original file content 4 try (FileWriter fw = new FileWriter(new File("F:\\hello.txt"));) { 5 6 // It means to add on the content of the original file 7 // FileWriter fw = new FileWriter(new File("F:\\hello.txt"), true); 8 fw.write("I have a dream!\n"); 9 fw.write("you need to have a dream!"); 10 11 // fw.flush(); 12 } catch (Exception e) { 13 } 14 } 15 }
3. Copy file
Code example: character stream copy text file
1 public class Main { 2 public static void main(String[] args) { 3 try (FileReader fr = new FileReader(new File("F:\\hello.txt")); 4 FileWriter fw = new FileWriter(new File("F:\\hello_copy.txt"));) { 5 6 char[] buff = new char[5]; 7 int len; 8 9 // Primary readout len Characters to buff. 10 while ((len = fr.read(buff)) != -1) { 11 fw.write(buff, 0, len); 12 fw.flush(); 13 } 14 } catch (Exception e) { 15 } 16 } 17 }
Note: character stream cannot be used to process byte data such as pictures and videos.
3, Byte stream
1. FileInputStream (input)
The basic usage is the same as character stream.
Code example: garbled code may appear when reading a file.
1 // File: F:\\hello.txt 2 // Content: helloworld123 Chinese 1 3 public class Main { 4 public static void main(String[] args) { 5 try (FileInputStream fis = new FileInputStream(new File("F:\\hello.txt"));) { 6 // fis.available():Returns the number of File Bytes 7 byte[] buffer = new byte[5]; 8 int len; 9 10 // Read by byte 11 while ((len = fis.read(buffer)) != -1) { 12 String str = new String(buffer, 0, len); 13 System.out.print(str); 14 } 15 } catch (Exception e) { 16 17 } 18 } 19 } 20 21 // result,Garbled code.The reason is that a Chinese character occupies two bytes,Divided. 22 helloworld123��country���1
2. FileOutputStream (output)
The basic usage is the same as character stream, except that flush() is not required when writing.
void write(int b): write one byte at a time
void write(byte[] b): write a byte array
void write(byte[] b, int off, int len): write a byte array, starting with off and the number of len bytes
Code example: writing files
1 public class Main { 2 public static void main(String[] args) { 3 try (FileOutputStream fos = new FileOutputStream(new File("F:\\hello.txt"));) { 4 5 fos.write("I have a dream!\n".getBytes()); 6 fos.write("you need to have a dream!".getBytes()); 7 8 } catch (Exception e) { 9 } 10 } 11 } 12 13 // result,Garbled code. 14 Yes a dream! 15 you need to have a dream!
Summary: because a Chinese character takes up two bytes. So,
Character stream, suitable for reading and writing text files. It is not applicable to byte stream and is prone to garbled code.
Byte stream, suitable for reading and writing binary files, such as pictures, audio, video, etc.
3. Copy file
Code example: use byte stream to process non text files (pictures, videos, etc.). Byte stream copies pictures.
1 // File: F:\\hello.PNG 2 public class Main { 3 public static void main(String[] args) { 4 try (FileInputStream fis = new FileInputStream(new File("F:\\hello.PNG")); 5 FileOutputStream fos = new FileOutputStream(new File("F:\\hello_1.PNG"));) { 6 7 byte[] buffer = new byte[5]; 8 int len; 9 10 // Read one at a time len Bytes to buffer. len <= buffer 11 while ((len = fis.read(buffer)) != -1) { 12 fos.write(buffer, 0, len); 13 } 14 } catch (Exception e) { 15 } 16 } 17 } 18 19 // This code is used to copy 3.64G File costs 56.574s