File class, recursive algorithm, IO stream

Posted by fredmeyer on Wed, 09 Feb 2022 03:46:11 +0100

1, File class

Class represents platform independent files and directories

File # can create, delete and rename files and directories, but file cannot access the file content itself. If you need to access the file content itself, you need to use input / output streams.

1. Constructor:

public class TestFile {
    public static void main(String[] args) {
    //The \ to write \ \ in the path can also be written/
    //Constructor of String parameter
    //File file1 = new File("D:/Lession/Java2113/temp.txt");
    //File file2 = new File("D:/Lession/Java2113/a.txt");
    //File(File parent, String child) constructor
    //File file1 = new File("D:/Lession/Java2113");
    //File file2 = new File(file1,"temp.txt");
    }
}
import java.io.File;
import java.io.IOException;

public class IOTest {
	public static void main(String[] args) {
		File f=new File("d:/huayu.txt");
		//If the file does not exist, a new file is created
		if(!f.exists()) {
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//Get the basic information of the file
		System.out.println(f.getName());
		System.out.println(f.getAbsolutePath());
		System.out.println(f.length());
		//Is it a normal file or directory
		System.out.println(f.isFile());
		System.out.println(f.isDirectory());
		//Delete file
		f.delete();
	}
}

2. Common methods:

createNewFile: creates an empty file

mkdir: create a folder (directory)

mkdirs: create multi-level folders

File file1 = new File("D:/Lession/Java2113/a/b/c");
//file1.mkdir();
//Create multi-level folder
file1.mkdirs();

Delete: delete a file or folder. It can only be deleted when the folder is an empty directory; If you want to delete a non empty folder, you can use a recursive algorithm.

Exists: determines whether a file or folder exists

getPath: get the path of the file (encapsulated path)

toString: equivalent to getPath()

getAbsolutePath: get its absolute path

getName: get the name of the file or folder

getParent: get the path of the file directory

isFile / isDirectory: judge whether the file object is a file or a folder

length: file size, in bytes

listFiles: get an array of all files and folder objects in the current folder

File file = new File("D:\\Lession\\Java2113\\preheat");
File[] files = file.listFiles();
for(File f:files) {
    System.out.println(f);
}

2, Recursive method

1. recursion

• Definition of recursion

If an object partially contains itself or defines itself by itself, the object is said to be recursive; If a procedure calls itself directly or indirectly, it is called a recursive procedure

• Recursive thought

The basic idea of recursion is to transform the large-scale problem into several similar sub problems with small-scale

• there are two types of recursion:

(1) direct recursion: call yourself

(2) Indirect recursion: A Call in B , B Called again in A

Invoke one's own method in the method

public class TestDG {
    //Method of calculating n factorial
    public static int jc(int n) {
    if(n==1)
        return 1;
        return jc(n-1)*n;
    }
    public static void main(String[] args) {
        System.out.println(jc(3));
    }
}

2. Three elements of recursion

1). Explicit recursive termination condition

Recursion should have a clear critical point. Once the program reaches this critical point, it doesn't need to continue to call recursively. In other words, the critical point is a simple situation that prevents infinite recursion.

2). The handling method of recursive termination is given

There is a simple situation at the critical point of recursion. In this simple situation, the solution to the problem should be given directly. Generally, in this situation, the solution of the problem is intuitive and easy.

3). Extract duplicate logic and reduce the scale of the problem

The recursive problem must be decomposed into several small-scale subproblems with the same form as the original problem, which can be solved with the same problem-solving ideas. From the perspective of program implementation, we need to abstract a clean and repetitive logic in order to solve the sub problems in the same way.

 3. recursive template

public Return value recursion(){
    //1. Recursive end condition
    if(){
        
    }
    //2. Business code

    //3. Downward recursive call
    recursion();

    //4. Empty and deal with the aftermath (not necessary)
}

Example: recursively delete files

Delete all files in non empty directory

/**
	 * Directory, non empty, delete all files;
	 */
	public static void delete(File f) {
		//1. End conditions
		if(f.isDirectory()) {
			//Find all sub files;
			File[] fs=f.listFiles();
			for(File file:fs) {
				//3. Call down
				delete(file);
				
			}
		}
		//2. Business code
		f.delete();	
	}

Find all in a folder java file

public class TestFile {
    public static void main(String[] args) {
        File file = new File("D:\\Lession\\Java2113\\preheat");
        delete(file);
    }
    //Find all java files in the "preheating folder" and store them in the List collection
    public static void getFile(File file,List<File> list) {
        String hzm = "";
        String name = "";
        int index = -1;
        //Determine whether file is a folder
        if(file.isDirectory()) {
            File[] files = file.listFiles();
            for(File f:files) {
                if(f.isDirectory()) {
                    getFile(f,list);
                }else {
                    name = f.getName();
                    index = name.lastIndexOf(".");
                    if(index!=-1) {
                        hzm = name.substring(index);
                    }
                    if(".java".equals(hzm)) {
                        list.add(f);
                    }
                }
            }
        }
    }
    //Delete all files and folders under the folder
    public static void delete(File file) {
        //Obtain existing files and folders
        File[] files = file.listFiles();
        //If it is a file, delete it
        for(File f:files) {
            if(f.isDirectory()) {
                delete(f);
            }
            //Delete the current folder or folder
            f.delete();
        }
        file.delete();
    }
}

3, IO stream (Input / Output stream: Input / Output)

IO data stream is an ordered binary data. Java IO stream is actually some IO stream tool classes

• Usually, the program needs to obtain / output information from the outside
• This "external" scope is very wide, including keyboard, display, file, disk, network, another program, etc
• "Information" can also be any type, such as an object, string character, image, sound, etc

• by using Java The input / output stream class in io package can achieve the purpose of input and output information

Classification of IO streams

1. Input stream and output stream: classification in direction, taking the memory as the angle. For example, the programming can copy a file from the U SB flash disk to a file on the hard disk, read the content with the input stream, and write the content with the output stream. The subclasses of InputStream and Reader are input streams; Subclasses of OutputStream and Writer are output streams

2. Byte stream and character stream: classification of processing data volume, that is, if one byte is read / written every time, then this stream is byte stream; Generally, Chinese is processed and character stream is used when displaying Chinese. Subclasses of InputStream and OutputStream classes are byte streams; Subclasses of Reader and Writer are character streams

3. Node flow and processing flow: node flow is called basic flow; Processing flow is also called high-level flow; Processing flow is the encapsulation of node flow, that is, processing flow adds additional functions on the basis of node flow. Node flow can handle all functional requirements, but its efficiency is low. Processing flow can handle specific requirements with high efficiency

FileInputStream

public class TestFile {
    public static void main(String[] args) {
        //Read temp Txt file content
        //The stream must be closed after use!!! Write in finally
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("D:\\Lession\\Java2113\\temp.txt");
            int temp = 0;
            while((temp = fis.read())!=-1) {
                System.out.println(temp);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

Topics: Java Back-end recursion