[JAVA Basics] Detailed explanation of IO

[JAVA Basics] Detailed explanation of IO

I. Overview

A stream is a sequenced set of bytes with a starting point and an end point. It is a general term or abstraction for data transmission. The transmission of data between two devices is called a stream. The essence of a stream is data transmission. The stream is abstracted into various classes according to the data transmission characteristics to facilitate more intuitive data operations.

2. The role of IO stream

Realize data transfer between two object devices.

3. Usage scenarios of IO stream

  1. When we use the File class, we can only perform file operations, including: obtaining file attributes, creating, deleting, moving files, etc., but we cannot make changes to the content of the file. If you want to operate on the file content, you need to read, delete the file content, etc.
  2. Usage scenarios of IO streams: When you need to operate on the contents of a file.

The operation object of the IO stream is a file, rather than reading and writing a folder. When using IO streams, be careful not to establish a connection with a folder.

4. Classification of IO streams

It is divided into different IO streams according to different classification standards:

4.1 Unit points for transmitting data:
  • Byte stream: What is transmitted is bytes, and the unit is bytes. The minimum unit for reading a byte stream is one byte (1byte=8bit). Can operate on any type of data.
  • Character stream: Bytes are transmitted, and one character can be read at a time (1char = 2byte = 16bit). The difference is that the encoding operation is added during the transmission process, making our operation more convenient.
4.2 Direction of data transmission:
  • **Input stream input:** Read external data (data from storage devices such as disks and optical disks) into the program (memory)
  • **Output stream output:** Output program (memory) data to storage devices such as disks and optical disks
4.3 Different roles of flow:
  • Node stream: A stream that reads and writes data directly from a source (this stream is not packaged or modified). The processing stream is a stream based on the encapsulation of the node stream. FileInputStream is a node stream that can read data directly from a file, but BufferedInputStream can wrap FileInputStream to make it have buffering function.
  • Processing stream: It is used to connect and encapsulate an existing node stream, and realize the read and write capabilities of the stream through the encapsulated stream. When using processing streams, the program does not connect directly to the actual data source, but instead connects to an existing stream.

5. IO stream system

Classification Byte input stream Byte output stream character input stream character output stream
abstract base class InputStream OutputStream Reader Writer
access files FileInputStream FileOutputStream FileReader OutWriter
access array ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter
access pipe PipedInputStream PipedOutputStream PipedReader PipeWriter
access string InputStreamReader OutputStreamWriter
buffered stream BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
Conversion flow InputStreamReader OutputSteamReader
object stream ObjectInputStream ObjectOutputStream
FilterInputStream FilterOutputStream FilterReader FilterWriter
print stream PrintStream PrintWriter
Push back the input stream PushbackInputStream PushbackReader
special stream DataInputStream DataOutputStream

6. Byte input stream InputStream

InputStream is a virtual class, which is a character input stream in Java, used to read data from files into Java programs.

The most commonly used method is: FileInputStream

  • Common methods

    1. int read(): Read one byte of data from the file. And return the byte read. If the reading is completed, the return value is -1;
    2. int read(byte[] b): Read one byte array at a time. The input stream will put the read content into this byte array and return the read number. If the reading is completed, -1 will be returned. ;
    3. void close(); close the byte stream;
  • FileInputStream implementation steps

    1. Create a FileInputStream stream object and bind a data source file
    2. Call the read method to read data
    3. Release resources
  • Sample code

    public  void inputStreamMethod() throws Exception  {
          
          
         FileInputStream in=new FileInputStream("D:\\goyeer.txt");
         //创建Fileinptstream 流对象,并绑定源文件
         byte[] buf=new byte[1024];
         int len;
         //调用read方法读取数据
         while((len=in.read(buf))!= -1){
          
          
             String line=new String(buf,0,len,"UTF-8");
             System.out.println(line);
         }
    }
    
  • InputStream system
    Insert image description here

7. Byte output stream OutputStream

The OutputStream class is the base class for all output streams in the Java IO API. Subclasses include BufferedOutputStream, FileOutputStream, etc. OutputStream is a typical decoration mode, which can be directly subclassed when used. OutputStream can output to console, files, disks and other target media.

  • Common methods

    1. void close(); Closes the output stream to prevent resources from being heavily occupied, which may eventually lead to handle overflow or memory overflow.
    2. void write(int b); the only abstract method in an abstract class. Non-abstract subclasses must implement this method.
    3. void write(byte b[]) directly outputs the entire contents of a byte array.
    4. void write(byte b[], int off, int len) The content to be output has been stored in the byte array b[], but not all of it is output. Only len bytes starting from the off position of the array are output.
    5. void lush() flushes the output stream and outputs all buffered bytes. Since some streams support caching, this method will force all content in the cache to be output to the stream.
  • OutputStream implementation steps

    1. Create an OutputStream stream object
    2. write method input
    3. close closes the stream to prevent memory overflow
  • Sample code

     public void outputStreamMethod() throws IOException{
          
          
            OutputStream ou=new FileOutputStream("D:\\ShowCoding.txt");
            String str = "欢迎Goyeer社区";
            byte[] bytes = str.getBytes();
            for(int i = 0; i < bytes.length; i++) {
          
          
                ou.write(bytes[i]);
            }
            ou.close();
      }
    
  • OutputStream system
    Insert image description here

8. Character input stream Reader

Reader is the parent class of the input character stream. It is an abstract class and is not recommended for file reading and writing.

  • Common methods

    1. void close(); Close the stream and release all resources associated with it;
    2. void mark(int readAheadLimit); mark the current position in the stream;
    3. boolean markSupported(); determines whether this stream supports the mark() operation;
    4. int read(); read a single character;
    5. int read(char[] cbuf); Read characters into array;
    6. int read(char[] cbuf, int off, int len); Read characters into a certain part of the array;
    7. int read(CharBuffer target) ;Attempts to read characters into the specified character buffer
    8. boolean ready() ; Determine whether this stream is ready to be read;
    9. void reset();Reset the stream
    10. long skip(long n); skip characters
  • Reader implementation steps

    1. Creates a file reading stream object associated with the file with the specified name; the file is guaranteed to exist. When the file does not exist, an exception (FileNotFoundException) occurs;
    2. Call the read method of the read stream object to read one character at a time and automatically read subsequent characters;
    3. Call the method to close the character stream;
  • Sample code

    public static void readerMethod() throws IOException{
          
          
        Reader reader=new FileReader("D:\\goyeer.txt");
        int ch = 0;
        char [] buf= new char[1024];
        while((ch=reader.read(buf))!=-1){
          
          
             System.out.print(new String(buf,0,ch));
        }
        reader.close();
    }
    
  • Reader system
    Insert image description here

9. Character output process Writer

The Writer class is the base class of all Writers in Java IO. It is an abstract class located under the java.io package. Implement subclasses that implement Writer, including BufferedWriter and PrintWriter.

  • Common methods

    1. Writer append(char c) adds the specified character to this write
    2. Writer append(CharSequence csq) adds the specified character sequence to this writer
    3. Writer append(CharSequence csq, int start, int end) adds a subsequence of the specified character sequence to this writer.Appendable
    4. abstract void close() closes this stream, but flushes it first
    5. abstract void flush() refreshes the buffer of this stream
    6. void write(char[] cbuf) writes character array
    7. abstract void write(char[] cbuf, int off, int len) writes a certain part of the character array
    8. void write(int c) writes a single character
    9. void write(String str) writes string
    10. void write(String str, int off, int len) writes a certain part of the string
  • Writer implementation steps

    1. Instantiate Writer via subclass
    2. Implement file writing operations through the write method
    3. close closes the output stream and releases resources.
  • Sample code

    public static  void writeMethod() throws IOException {
          
          
       Writer out = new FileWriter("D:\\goyeer.log");
       String str = "I/O字符流,Writer类应用。";        
       out.write(str);
       out.close();
    }
    
  • Writer system
    Insert image description here

10. Summary

Java IO is the Java input and output system, namely in and out, which refers to the data transfer between applications and external devices. Common external devices include files, pipes, and network connections. When writing a program, choose the byte stream and character stream that suits your scenario, and use abstract subclasses flexibly.

Guess you like

Origin blog.csdn.net/songjianlong/article/details/132443181