JAVA - Advanced IO flow: function flow and commonsio tool class

Posted by cfemocha on Sat, 29 Jan 2022 02:09:13 +0100

JAVA - Advanced IO flow: function flow and commonsio tool class

1, Function flow (processing flow)

Function flow is to enhance and improve performance, and it does not have the ability to directly operate nodes.

1.1 Buffered cache stream

One type of function flow:
Buffered streams: enhancements to improve performance
Usage: function flow (node flow)

Byte buffer stream:
Byte input buffer stream BufferedInputStream
Byte output buffer stream BufferedOutputStream
There is no new method, and polymorphism can occur

Character buffer stream:
BufferedReader adds a new method readLine() to read a line
BufferedWriter adds a new method newLine() to write out line breaks
Polymorphism cannot occur because the parent class reference is not visible to the new method of the child class

Example code: byte input buffer stream BufferedInputStream

    //1. Create source and establish contact
    File src =new File("test.txt");
    //2. Select buffer stream
    InputStream is =new BufferedInputStream(new FileInputStream(src));
    //3. Operation: multiple reads
    byte[] car =new byte[2];
    int len =0;
    while(-1!=(len=is.read(car))){
        //Get the contents of the array byte array to string new string (byte array, 0,length)
        System.out.println(new String(car,0,len));
    }
    //4. Release resources
    is.close();

Character input buffer stream BufferedReader

    //Create source:
    File src =new File("test.txt");
    //Use character buffer stream to improve performance, read files + add new methods (polymorphism cannot be used)
    BufferedReader br =new BufferedReader(new FileReader(src));
    //Operation line reading
    String line=null;
	//readLine() can directly read a line of data
    while(null!=(line=br.readLine())){
        System.out.println(line);
    }
    //Release resources
    br.close();

1.2 data processing flow

DataInputStream basic data type input stream
New method: read... ();
DataOutputStream basic data type input stream
New method: write... ();

You must write before you read. The order of reading must be consistent with the order of writing

It can handle basic type + String and retain the type of data. The premise is that the reading order is consistent with the writing order, otherwise the read data is incorrect

/**
* Data + type output to file
* @param destPath
* @throws IOException
*/
public static void write(String destPath) throws IOException{
    int point = 2;
    long num = 100L;
    String str = "data type";
    //Create source
    File dest = new File(destPath);
    //Select flow
    DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest)));
    //The order in which operations are written out prepares for reading
    dos.writeInt(point);
    dos.writeLong(num);
    dos.writeUTF(str);
    dos.flush();
    //Release resources
    dos.close();
}

1.3 Object flow

Function: the data type (reference data type | basic data type) that can read and write data and retain data

Serialization: convert the data of object type into a process that can be stored and transmitted

Deserialization: reverse the state (to the object format in java)

ObjectInputStream    Deserialize input stream
    New method: Object readObject() from ObjectInputStream Read an object from.
ObjectOutputStream   Serialize output stream
    New method: void writeObject(Object obj) Writes the specified object to ObjectOutputStream. 

be careful:

  1. Serialize before deserialize
  2. The order of reading and writing should be consistent
  3. Not all types of data can be serialized. You need to implement an empty interface java io. Serializable
  4. Not all attributes need to serialize the transient modifier
  5. Static variables are not serialized
  6. The parent class has a serialization interface, and the child class can sequence all members
  7. The subclass implements the serialization interface, the parent class does not implement it, and the subclass can only serialize its own unique content

serialize

package com.xxxx.myio;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
/*
Serialize an object to a file
*/
public class Demo005 {
    public static void main(String[] args) throws Exception {
        // Determine destination
        File file = new File("a.txt");
        // Select flow
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        // Write data
        Student stu = new Student("zas",18,false);
        oos.writeObject(stu);
        oos.flush();
        // Release resources
        oos.close();
    }
}

Deserialization

/**
* Deserialization:
* 1,Write before read
* 2,To read objects, you need to know the specific types and read them in turn
* be careful:
* 1)Not all objects can be serialized Serializable
* 2)Not all attributes need to serialize transient
*/
public static void read(String srcPath) throws FileNotFoundException,IOException, ClassNotFoundException{
    //Create source
    File src=new File(srcPath);
    //Select stream OjbectInputStream
    ObjectInputStream dis=new ObjectInputStream(new BufferedInputStream(new FileInputStream(src)));
    //The read order of the operation is consistent with the write order. It can only be read if it exists
    Object obj=dis.readObject();
    if(obj instanceof Employee){
        Employee emp=(Employee)obj;
        System.out.println(emp.getName());
        System.out.println(emp.getSalary());
    }
    obj=dis.readObject();
    int[]arr=(int[])obj;
    System.out.println(Arrays.toString(arr));
    //Release resources
    dis.close();
}

2, Common IO tool class

CommonsIO is an open source toolkit of apache, which encapsulates the relevant classes of IO operations. Using commons IO can easily read and write files, URLs, source code, etc. Commons IO needs to add the class file in the third-party jar package of classpath to be used in the project

2.1 IO tools IOUtils

This method has multiple overloaded methods to meet different input and output streams,

IOUtils.copy(InputStream input, OutputStream output) 

This method is suitable for copying large data streams, such as 2G or more. By default, 1024 * 4 buffer will be used to read

IOUtils.copyLarge(Reader input, Writer output)  

Get the input stream through text, and you can specify the encoding format

IOUtils.toInputStream(String input, String encoding)

Get a buffered input stream. The default buffer size is 1KB. You can also specify the buffer size

IOUtils.toBufferedInputStream(InputStream input) 

Gets a character buffer stream. The buffer size can be specified

IOUtils.toBufferedReader(Reader reader) 

2.2 IO tool class FilenameUtils

This tool class is used to handle file names (file paths), which can easily solve the problem of different file name specifications for different operating systems,

The methods inside are static and can be called directly with classes

FilenameUtils.getBaseName(String filename) // Remove the file name after the directory and suffix
FilenameUtils.getExtension(String filename) // Gets the suffix of the file
FilenameUtils.getName(String filename) // Get file name
FilenameUtils.getPath(String filename) // Path after removing drive letter
FilenameUtils.getPrefix(String filename) // Drive letter
isExtension(String fileName, String text) // Determine whether fileName is a text suffix

2.3 IO tool class FileUtils

Copy folder

Copy the folder (the contents of the files in the folder will also be copied)

FileUtils.copyDirectory(File srcDir, File destDir) 

Copy folder with file filtering function

 FileUtils.copyDirectory(File srcDir, File destDir, FileFilter filter) 

Copy a folder as a subdirectory to another folder

FileUtils.copyDirectoryToDirectory(File srcDir, File destDir)

Copy file

Copy file

FileUtils.copyFile(File srcFile, File destFile)

Copy files to a specified directory

FileUtils.copyFileToDirectory(File srcFile, File destDir)

Write string to file

The string is written to the file in the specified encoding

FileUtils.writeStringToFile(File file, String data, String encoding)

Specify whether to append

FileUtils.writeStringToFile(File file, String data, String encoding, boolean append)

Byte array write file

Series methods, you can specify append, offset, etc

FileUtils.writeByteArrayToFile(File file, byte[] data) 

file move

move file

FileUtils.moveFile(File srcFile, File destFile)

Delete file

Delete folders, including folders and all files in folders

FileUtils.deleteDirectory(File directory)

Topics: Java