[Java] IO flow foundation

🏠: Blog home page: Incoming bogey
📕: Today's article: [Java] IO stream Foundation
💝: I hope my interpretation of the source code can help you 🎈
🌱: Boji is still trying to learn JavaSE. If you have any questions or omissions, please give me more advice 🙏
☀️: On the way of self-study and growth, thank you for your company! No hurry , No Pause ! 💝

1. Documents

Files are not unfamiliar to us. Files are places to save data, such as frequently used word documents, txt files, excel files... Are all files. It can save a picture, video, sound

1.2 file flow

Files are operated in the form of stream in the program

Stream: the path of data between data source (file) and program (memory);

Input stream: the path of data from data source (file) to program (memory);

Output stream: the path of data from program (memory) to data source (file);

1.3 common file operations

Constructors and methods related to creating file objects

  1. new File (String pathname) / / process a File object according to the path
  2. new File (String parent, String child) / / build according to the parent directory file + child path
  3. new File (String parent, String child) / / build according to parent directory + child path

Directory operation and file deletion

mkdir creates a first level directory, mkdirs creates a multi-level directory, and delete deletes empty directories or files
Code example:

// Method 1 new File(String pathname)
    @Test
    public void create01()  {
        String filepath = "e:\\new1.txt" ;
        File file = new File(filepath);

        try {
            file.createNewFile();
            System.out.println("File created successfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //Method 2 new file (file parent, string child) is built according to the parent directory file + child path
    // e:\\news2.txt
    @Test
    public void create02() {
        File parentFile = new File("e:\\") ;
        String fileName = "news2.txt" ;
        //The file object here, in a java program, is just a Java object
        //Only when the createFile method is executed can the file be truly created on the disk
        File file = new File(parentFile, fileName);

        try {
            file.createNewFile() ;
            System.out.println("Created successfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // new File (String parent, String child) / / build according to parent directory + child path
    @Test
    public void create03() {
        String parentPath = "e:\\" ;
        String filePath = "news3.txt";
        File file = new File(parentPath, filePath);
        try {
            file.createNewFile() ;
            System.out.println("Created successfully 01");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2. IO flow principle

2.1 basic introduction of I / O

  1. I/O is the abbreviation of input/Output. I/O technology is a very practical technology for processing data transmission. Such as reading / writing files, network communication, etc.:
  2. In Java program, the input and output operations of data are carried out in the way of "stream";
  3. java. Various "stream" classes and interfaces are provided under the IO package to obtain different kinds of data, and input and output data through methods;
  4. Input: read external data (data from disk, optical disc and other storage devices) into the program (memory);
  5. Output: output program (memory) data to disk, optical disc and other storage devices;

2.2 classification of flow


2.3 InputStream: byte input stream

2.3.1 FileInputStream: file input stream

Example code:

    //Low reading efficiency of single byte
    //Use read(byte[] b)
    @Test
    public void readFile01() {
        String filePath = "e:\\news2.txt" ;
        int readData = 0 ;
        FileInputStream fileInputStream = null ;
        try {
            //Create a FileInputStream object to read files
            fileInputStream = new FileInputStream(filePath);
            //Read one byte of data from the input stream. If no input is available, the slave method is blocked
            //If - 1 is returned, the reading is completed
            while ((readData = fileInputStream.read()) != -1) {
                System.out.print((char)readData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Close the file stream and free up resources
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

2.4 FileReader and FileWriter


2.5 node flow and processing flow


Differences and relations between node flow and processing flow

  1. Node flow is the bottom flow / low-level flow, which is directly connected with the data source;
  2. Processing flow (packaging flow) packaging node flow can not only eliminate the implementation differences of different node flows, but also provide a more convenient method to complete input and output;
  3. The processing flow (wrapping flow) wraps the node flow, using the decorator design pattern, and will not be directly connected to the data source

The processing flow function is mainly reflected in the following two aspects:

1. Performance improvement: mainly increase the buffer to improve the efficiency of input and output;
2. Convenient operation: the processing flow may provide a series of convenient methods to input and output large quantities of data at one time, which is more flexible and convenient to use;

2.6 processing flow

BufferedReader and BufferedWriter belong to character stream and read data according to characters

public class BufferedReader_ {
    public static void main(String[] args) throws  Exception{
        //Create a buffer flow object and socket it on the basis of the specified node flow
        //Note: because the Reader and Writer read by character, they cannot operate binary files (byte files), such as
        //Pictures, music, causing reading errors

        String filePath = "e:\\threadUse_.java" ;
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
        //read
        String line ; //Read by line, high efficiency
        //explain:
        //1.bufferedReader.readLine() is read by line
        //2. When null is returned, it indicates that the file has been read
        while((line = bufferedReader.readLine())!= null) {
            System.out.println(line);
        }

        //To close the flow, you only need to close BufferedReader, because the bottom layer will automatically close the node flow
        //FileReader
        bufferedReader.close();
    }
}

To close the processing flow, you only need to close the outer flow;

BufferedInputStream and BufferedOutputStream

BufferedInputStream is a byte stream. When creating BufferedInputStream, an internal buffer array will be created

BufferedOutputStream is a byte stream that implements buffered output stream. Multiple bytes can be written into the underlying output stream without calling the underlying system for each byte write

public class BufferedScreamCopy_ {
    public static void main(String[] args) {
        String src1FilePath = "e:\\boji.jpg" ;
        String des1FilePath = "d:\\boji.jpg" ;
        // create object
        BufferedInputStream bis = null ;
        BufferedOutputStream bos = null ;

        try {
            // FileInputStream is a subclass of InputStream
            bis = new BufferedInputStream(new FileInputStream(src1FilePath)) ;
            bos = new BufferedOutputStream(new FileOutputStream(des1FilePath)) ;

            //Loop to read the file and write to des1FilePath
            byte[] buff = new byte[1024] ;
            int readLen = 0 ;
             while ((readLen = bis.read(buff)) != -1) {
                 bos.write(buff, 0, readLen);
             }
            System.out.println("File copy complete..");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //Close the flow, close the outer processing flow, and the bottom will close the node flow{
                try {
                    if( bis != null)
                        bis.close();
                    if (bos != null) {
                        bos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

2.7 object flow


Object stream – ObjectInputStream and ObjectOutputStream

Look at a demand

  1. Save the int data type int num =100 to the file. Note that it is not a 100 number, but int 100. In addition, int 100 can be recovered directly from the file;
  2. Save the dog object dog = new dog ("Xiaohuang", 3) to a file and recover it from the file;
  3. The above requirement is to be able to serialize or deserialize basic data types or objects;

2.7.1 serialization and deserialization

  1. Serialization is to save the value and data type of data when saving data;

  2. Deserialization is to recover the value and type of data when recovering data;

  3. If an object needs to support serialization mechanism, its class must be serializable. In order to make a class serializable, the class must implement one of two interfaces:

    • Serializable / / this is a tag interface without methods
    • Exeternalizable / / this interface has methods to implement, so it generally implements the above Serializable interface

matters needing attention

  1. Read and write in the same order
  2. It is required to implement serialized and deserialized session objects, and serialable needs to be implemented
  3. SerialVersionUID is recommended to be added to serialized classes to improve version compatibility;
  4. When serializing an object, all serialization attributes are serialized by default, except for members decorated with static or transient
  5. When serializing an object, it is required that the type of the attribute inside should also implement the serialization interface
  6. Serialization is inheritable, that is, if a class has implemented serialization, all its subclasses have implemented serialization by default
public class ObjectInputStream {
    public static void main(String[] args) throws Exception{
        //After serialization, the saved file format is not text, but according to its format
        String filePath = "e:\\data.dat" ;
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath)) ;
        //Serialize data to e: \ \ data dat
        oos.writeInt(100); ; // Int - > integer (serializable implemented)
        oos.writeBoolean(true); // boolean -> Boolean
        oos.writeChar('a'); // char -> Character
        oos.writeDouble(8.5); // double -> Double
        oos.writeUTF("niHao"); //String

        oos.writeObject(new Dog1("jack", 10));

        oos.close();
        System.out.println("Data saved(serialized form )");

    }
}
public class ObjectOutputStream {
    public static void main(String[] args)throws Exception {
        //After serialization, the saved file format is not text, but according to its format
        String filePath = "e:\\data.dat" ;

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath)) ;

        //read
        //1. The order of reading (deserialization) should be consistent with the order in which you save data (serialization)
        //2. Otherwise, an exception will occur

        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readChar());
        System.out.println(ois.readDouble());
        System.out.println(ois.readUTF());
        //The compilation type of Dog is Object, and the running type of Dog is Dog
        Object dog = ois.readObject() ;
        System.out.println("Operation type=" + dog.getClass());
        System.out.println("dog information=" + dog); // Underlying object - > dog

        // If you need to call Dog's method, you need to transform down
        //We need to copy the Dog class definition to the reference location
        Dog dog2 = (Dog)dog ;
        System.out.println(dog2.getName());
        //Close the flow, just close the outer flow, and the bottom will close the FIleInputStream flow
        ois.close();
    }
}

Keywords: Java JavaSE

Added by phuggett on Thu, 17 Feb 2022 12:20:28 +0200