IO stream [Introduction to IO stream technology, classic writing of IO stream, classic writing of new grammar of IO stream, concept subdivision of stream in Java] (1) - comprehensive detailed explanation (learning summary --- from entry to deepening)

 

Table of contents

Introduction to IO stream technology

The first simple IO stream program 

 The classic way of writing IO stream

 IO Stream New Grammar Classic Writing

The conceptual breakdown of streams in Java 

 System of IO stream class in Java


 

Introduction to IO stream technology

 What is IO

Input (Input) refers to: the program can obtain data from an external system (the core meaning is "read", read external data). Output (Output) refers to: the program outputs data to the external system so that the external system can be operated (the core meaning is "write", write the data to the external system). The java.io package provides us with related APIs to implement input and output operations on all external systems. This is the technology we will learn in this chapter.

 What is a data source

Data source data source, which provides the original medium of data. Common data sources include: databases, files, other programs, memory, network connections, and IO devices. as the picture shows.

 

 The data source is divided into: source device and target device.

1 Source device: Provide data for the program, generally corresponding to the input stream.

2 Target device: The destination of the program data, generally corresponding to the output stream.

 flow concept

Stream is an abstract and dynamic concept, which is a series of continuous and dynamic data collections. For the input stream, the data source is like a water tank, the stream is like the water flowing in the water pipe, and the program is our final user. We transmit the data (information) in the data source (Source) to the program (Program) through the stream (A Stream). For the output stream, the target data source is the destination (dest), and we transfer the data (information) in the program (Program) to the destination data source (dest) through the stream (A Stream).

 Relationships between streams and source and target data sources:

 

 Oldlu Tips

The division of input/output streams is relative to the program, not relative to the data source.

 

The first simple IO stream program 

 When the program needs to read the data of the data source, it will open a stream to the data source through the IO stream object, and the data in the data source can be read sequentially through the related methods of the IO stream object.

Use stream to read file content (non-standard writing, only for testing)

import java.io.*;
public class TestI01 {
 public static void main(String[] args) {
 try {
 //创建输入流
 FileInputStream fis = new FileInputStream("d:/a.txt"); // 文件内容是:abc
 //一个字节一个字节的读取数据
 int s1 = fis.read(); // 打印输入字符a对应的ascii码值97
 int s2 = fis.read(); // 打印输入字符b对应的ascii码值98
 int s3 = fis.read(); // 打印输入字符c 对应的ascii码值99
 int s4 = fis.read(); // 由于文件内容已经读取完毕,返回-1
 System.out.println(s1);
 System.out.println(s2);
 System.out.println(s3);
 System.out.println(s4);
 // 流对象使用完,必须关闭!不然,总占用系统资源,最终会造成系统崩溃!
   fis.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
  }
}

In the above case, we should pay attention to the following points:

1. The content of the file we read is known, so we can use a fixed number of "int s= fis.read();" statements to read the content, but in actual development, we usually don't know the content of the file at all, so We need to use while loop when reading.

2. In order to ensure the normal closing of the stream after an exception occurs, usually the closing statement of the stream should be placed in the finally statement block, and it is necessary to judge whether the stream is null.

 

 The classic way of writing IO stream

 

 Use stream to read file content (classic code, must master)

import java.io.*;
public class Test2 {
 public static void main(String[] args) {
 FileInputStream fis = null;
 try {
       fis = new FileInputStream("d:/a.txt"); // 内容是:abc
       StringBuilder sb = new StringBuilder();
       int temp = 0;
      //当temp等于-1时,表示已经到了文件结尾,停止读取
      while ((temp = fis.read()) !=-1) {
         sb.append((char) temp);
     }
         System.out.println(sb);
 } catch (Exception e) {
         e.printStackTrace();
 } finally {
 try {
 //这种写法,保证了即使遇到异常情况,也会关闭流对象。
 if (fis != null) {
      fis.close();
     }
  } catch (IOException e) {
      e.printStackTrace();
    }
   }
 }
}

 

 IO Stream New Grammar Classic Writing

 In JDK7 and later versions, you can use the try-with-resource syntax to close resources more gracefully. java.lang.AutoCloseable interface: The java.lang.AutoCloseable interface contains a close method, which is used to close resources. As long as the object implements the java.lang.AutoCloseable interface, you can use try-with-resource to close the resource. Use the latest try-with-resource simplification (classic code, must master)

public class Test3 {
    public static void main(String[] args) {
        //使用try-with-resource方式关闭资源。
        //在try中打开资源,不需要在代码中添加finally块关闭资源。
        try(FileInputStream fis = new FileInputStream("d:/a.txt");){
            StringBuilder sb = new StringBuilder();
            int temp=0;
            while((temp = fis.read()) != -1)
           {
                sb.append((char) temp);
           }
            System.out.println(sb);
       }catch(Exception e){
            e.printStackTrace();
       }
   }

Oldlu suggested that the above code is a very typical IO stream code, and the use of other stream objects is basically the same pattern!

 

The conceptual breakdown of streams in Java 

 Classified by direction of flow:

 Input stream: The data flow direction is from the data source to the program (the stream ending with InputStream, Reader).

 Output stream: The data flow is from the program to the destination (the stream ending with OutPutStream, Writer).

 Classified by data unit processed:

Byte stream: Obtain data in units of bytes. The streams whose names end with Stream are generally byte streams, such as FileInputStream and FileOutputStream.

Character stream: Get data in units of characters, and the stream whose name ends with Reader/Writer is generally a character stream, such as FileReader and FileWriter.

 According to different classifications of processing objects:

Node Stream: You can read and write data directly from the data source or destination, such as FileInputStream, FileReader, DataInputStream, etc.

Processing streams: Not directly connected to data sources or destinations, are "flows of processing streams". Improve program performance by processing other streams, such as BufferedInputStream, BufferedReader, etc. Process streams are also called wrapper streams.

 Node streams are at the front line of IO operations, and all operations must be performed through them; processing streams can package node streams to improve performance or program flexibility.

 

 System of IO stream class in Java

Java provides us with a variety of IO streams. We can choose the appropriate IO stream according to different functions and performance requirements. As shown in the figure, it is the system of IO streams in Java.

 Note: Only commonly used classes are listed here. For details, please refer to the JDK API documentation.

 From the figure above, it is found that many streams appear in pairs, such as: FileInputStream/FileOutputStream, which obviously perform input and output operations on files. Let's make a brief summary below:

1 InputStream/OutputStream Abstract class of byte stream.

2 Reader/Writer Abstract class for character streams.

3 FileInputStream/FileOutputStream node stream: direct operation of "file" in bytes.

4 ByteArrayInputStream/ByteArrayOutputStream node stream: Directly manipulate the "byte array object" in units of bytes.

5 ObjectInputStream/ObjectOutputStream processing stream: direct manipulation of "object" in units of bytes.

6 DataInputStream/DataOutputStream processing stream: directly manipulate "basic data types and string types" in units of bytes.

7 FileReader/FileWriter node stream: directly operate "text files" in units of characters (note: only read and write text files).

8 BufferedReader/BufferedWriter processing flow: wrap the Reader/Writer object, increase the cache function, and improve the read and write efficiency.

9 BufferedInputStream/BufferedOutputStream processing stream: wrap the InputStream/OutputStream object, increase the cache function, and improve the read and write efficiency

10 InputStreamReader/OutputStreamWriter process stream: convert byte stream object into character stream object.

11 PrintStream processing stream: Wrap OutputStream to output characters conveniently, which is more flexible.

Oldlu suggested the above explanation, which hits the core role of flow in one sentence. When you study later, you should experience it with your heart. 

 

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/131647239