Java learning notes - io stream

Keywords: Java IntelliJ IDEA

io usage scenarios

When we want to store some data in the disk so that the data can be found when the program closes and runs again, we need to write the data out of the program with io stream, write it to the local file, or save it to the database, etc.

iO details

Check the java API documentation -- java.base -- java.io. It is found that there are many interfaces, classes and method calls (in short, it is a bit messy). Here are the following ↓

  Therefore, from a macro point of view, simply classify them, and then decompose them for learning:

io classification

According to reading unit:

Byte stream (one byte at a time, 8bit) (any data can be processed)

Character stream (java one character 16bit) (can only handle character types)

According to the output and input directions: (the methods of byte and character streams in different directions)

Input stream (read data from memory file, cache, keyboard)

Output stream (write data to memory, cache, console, etc.)

//Character stream:
read      
writer

//Byte stream:
inputStream
outputStream

According to the target node: (where to read from and where to write to. That is, the container types are different. It feels a little corresponding to the data types to read and write, but not exactly. After all, the file stream can read and write data of basic types such as int and String)

Array ByteArray, CharArray

String string

object

file

Pipe (read data from a pipe shared with other threads)

data,

Cache buffer (avoid frequent hard disk read and write operations)

print data (to console)

Sequence (output stream sequence)

filter (I don't quite understand this)

Character stream, byte stream interchange, etc.

  • (my understanding: the input and output streams of the above characters and bytes are four parent classes. You can design your own personalized rewriting methods for where you want to read in, where to read out the data, the operation data type of reading and writing, and in what order to read in and read out... Of course, java instantiates the specific methods mentioned above. Basically, each parent class has Derivations have the above subclasses < but some only have inputStream and outputStream, but read and writer do not, and vice versa. >, the naming is generally: type + parent class name is suffix)

  • The API document says:
  1. reader:
  2. writer:
  3. inputStream:
  4. outputStream:

Classification is basically the above

Two excellent bloggers have given the mind map (very clear der, worship it)

It seems that they are similar and complement each other a little (I will attach the articles of the big guys later)

io exception

The Java API document also gives io exceptions (throwing exceptions must be added when many methods are used):

usage method

//I will demonstrate the following usage of the four parent classes:

//1. Declare a file object
File filename = new File("file name");

//2. Declare an input or output stream object + read / write operation (select the stream according to the object or target node of the operation)
//Byte: read data from file to num:
int num = 123;
FileInputStream fileInputStream = new FileInputStream(Gets the file object of the data)
num = fileinputStream.read(); //Assign the read data to num

//Byte: writes data to a file
FileOutputStream  fileOutputStream =  new FileOutputStream(File object written)
fileOutputStream.write(num)  //Write data num to file

//Characters: read from file
FileReader fr = new FileReader("demo.txt");
num = fr.read();

//Characters: writing to files
FileWriter fw = new FileWriter("demo.txt");
fw.write(num);


//3. Close flow operation
fileInputStream.close()
fileOutputStream.close()
fr.close();
fw.close();


//ps:
//1. Other types of reading and writing are similar, but they are basically three processes
//2. There are many settings for file reading and writing, such as whether to overwrite the original content or write at the end of the file

Some details of the principle of read-write mechanism

(because I only practiced the reading and writing of file stream temporarily, so only focused on the analysis of file stream)

  1. When reading data, FileInputStream reads one byte at a time, 8bit;
  2. FileInputStream reads from the beginning of the file. After reading 1 byte each time, the pointer remains at the current position. Therefore, the second byte is read again until the file is empty. If the data is not read, it will return - 1.
  3. FileOutputStream writes data to the file one byte at a time. If the data type written is greater than 1 byte, it will write the lower eight bits by default.
  4. FileOutputStream writes data to the end of the file every time.
  5. FileInputStream: if the file to be read does not actually exist, an exception will be reported; If the file to be written by FileOutputStream does not actually exist, it will automatically create a new file in the program directory and write the data.
  6. Based on the above knowledge, pay attention to the order when writing multiple byte data objects to the file and then reading them out.
  7. Assuming reading and writing num (int type), the following is a schematic diagram:

Exercise Code: design your own class to write / write int type data to / from the file

The idea of connection: make sure to read in an int and write out the int i want; The order of reading in multiple data is consistent with the order of reading out.

//IntIo.java

import java.io.*;

public class IntIO {
    private File file;
    public IntIO(File file){           //Constructor: pass in the file you want to read / write
        this.file = file;
    }
    public void writer(int number) throws IOException {  //Write operation: write 4 times, starting from the low byte
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(number);
        fileOutputStream.write(number>>>8);
        fileOutputStream.write(number>>>16);
        fileOutputStream.write(number>>>24);
        System.out.println("Write succeeded!");
    }
    public int reader() throws IOException {      //Read operation: read 4 times, read out the low byte first, take different byte and adjust the position separately.
        FileInputStream fileInputStream = new FileInputStream(file);
        int num1 = fileInputStream.read();
        int num2 = (fileInputStream.read())<<8;
        int num3 = (fileInputStream.read())<<16;
        int num4 = (fileInputStream.read())<<24;
        return (num1+num2+num3+num4);
    }

}


//Test.java

import java.io.File;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        IntIO intIO = new IntIO(new File("text.txt"));
        intIO.writer(1000);
        System.out.println(intIO.reader());
    }
}

Learning article: big man blog

Java - IO stream super detailed summary - story telling five childe - blog Garden          -> How to use the code to explain the method is super clear

Java IO stream learning summary 1: input / output stream_ Zhao Yanjun - CSDN blog_ javaio stream    -> The logic is first-class, and the classification and relationship of several streams are relatively complete

I don't know what a filter is. Although this article doesn't say what it is used for, there are code examples to see and understand:

Java_ Introduction, source code and examples of FilterWriter and FilterReader of IO system - 15_ Oscar Chen CSDN blog

Posted by chalexan on Sat, 30 Oct 2021 02:04:49 -0700