IO stream technology
What is an IO stream??? I represents input (read) and O represents output (write). The input and output here represents the data interaction between the JAVA program and the external disk file or server. Input indicates that the external file is input to the JAVA program, and output indicates that the JAVA program is output to the outside.
1. Classification of flow
- From the direction of flow, it is divided into input flow and output flow
- The unit of data transmitted from a stream is divided into byte stream and character stream
- For the construction of flow, it is divided into basic flow and packaging flow
2. Flow we need to master
Here I draw a diagram for byte stream and character stream. What is marked in red is that we need to master its principle.
- The byte stream is as follows:
- The character stream is as follows:
- Here, I will list several mastered flows on the figure:
FileInputStream,FileOutputStream (these are basic streams)
BufferedInputStream,BufferedOutputStream
ObjectInputerStream,ObjectOutputStream
FileReader and filewriter (these are basic streams)
Inputstreamreader, outputstreamwriter (conversion stream, also character stream)
BufferedReader,BufferedWriter
law:
1. Input or reader in the name is used for input (reading), and output or Writer in the name is used for output (writing).
2. Class names with streams are byte streams, and those with reader s or writer s are character streams.
3. Packaging flow cannot be used directly. It can only be used after packaging based on basic flow.
3. Byte stream
3.1 FileInputStream and FileOutputStream
These two streams belong to byte streams, and the contents of a file are obtained in bytes.
After the file stream is used, it must be closed manually. All stream objects uniformly implement the Closeable interface. In order to ensure that the flow closing code must be executed, we write the closing code in the finally block.
Case: use byte input / output stream to copy a picture file (don't take too long).
public static void main(String[] args) { FileInputStream fis =null; FileOutputStream fio = null; try { fis = new FileInputStream("D:\\zzz\\test.png"); fio = new FileOutputStream("D:\\bbb\\test.png"); byte[] buffer = new byte[1024]; int r; while((r=fis.read())!=-1) { fio.write(buffer,0,r); } fio.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { if(fis!=null) { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(fio!=null) { try { fio.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
- This paper proposes a concept of Decorator Pattern: enhancing the function of the original class in some aspects. For example, the BufferedInputStream class actually defines an InputStream type attribute, and requires a basic stream to be passed in during construction. Whether the user calls the read method of the stream object or the reaad method of the basic stream is actually a buffer enhancement in the process of reading the file, which improves the file reading efficiency.
3.2 BufferedInputStream and BufferedOutputStream
- Byte input / output stream with buffer is a wrapper stream.
BufferedInputStream bis=new BufferedInputStream(new FileInputStream("d:\\zz.txt")) BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("D:\\a.txt")) int r; while((r=bis.read())!=-1) { bos.wriite(r); } //Exception not handled
3.3 ObjectInputerStream and ObjectOutputStream
- Object input / output stream: the process of converting a JAVA object into a byte sequence is called "object serialization", which aims to save the object on disk or transmit it on the network. In JAVA, the serialization and deserialization of objects are realized through the input and output streams of objects.
1. Serialization: convert JAVA objects into byte sequences, and perform output operations to sequence JAVA objects.
2. Deserialization: restore the byte sequence to a JAVA object and input the byte sequence.
Note: classes that need to be serialized must implement the Serializable interface. This interface is an empty interface. This interface is mainly used for marking. While implementing the Serializable interface, it is recommended to provide a constant in the current class:
private static final long serialVersionUID = -3308982073920623004L; Representation order
The version number of the column
If we do not want an attribute of an object to participate in the process of serialization and deserialization, we can use the transient keyword to modify the attribute.
//Serialization (output, write) Person person=new Person("Zhang San",18,"male"); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\person.data")); oos.writeObject(person); oos.flush(); //Deserialization (input, read) ObjectInputStream ois=new ObjectInputStream(new FileInputStream("D:\\person.data")); //ois.readObject is an Object type and needs to be transformed downward to the subclass type Person Person person =(Person)ois.readObject(); //Exception not handled
4. Character stream
When we read a text information, it is obviously inappropriate to read in bytes, because some characters do not occupy a byte of space when stored. Therefore, in order to make it easier to read the content of text information, Java provides us with a stream: character input and output stream.
4.1 FileReader and FileWriter
These are the basic flows.
FileReader reader=new FileReader("D:\\aaa.txt"); //Buffer array char[] arr = new char[3]; reader.read(arr); System.out.println(new String(arr));
4.2 BufferedReader and BufferedWriter
- The character input / output stream with its own buffer is a wrapper stream. BufferedReader can not only improve the efficiency of submission and reading, but also be very convenient. The stream object provides us with a readLine() for reading text files in behavioral units
BufferedReader reader=new BufferedReader(new FileReader("D:\\TestFileOutputStream.java")); StringBuffer sb=new StringBuffer(""); String line=null; while((line=reader.readLine())!=null) { //Read the contents of the text file line by line sb.append(line + "\r\n"); }
BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\test.txt")); String[] arr=new String[] {"Hello","What do you have for dinner?","What are you doing after dinner"}; for (String s : arr) { bw.write(s); bw.newLine();//Create a new row } bw.flush();
4.3 InputStreamReader and OutputStreamWriter
-
These two are a wrapper flow and a transformation flow.
Little cheese: the root of all garbled code lies in the inconsistent format of information coding and decoding. -
The encoding and decoding methods cannot be specified during the construction of character stream. Only the character set can be specified during the creation of byte stream.
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("D:\TestFileOutputStream.java"),"utf-8"));