java Foundation (22):File, recursion

1. File

1.1 Overview of IO

Looking back on the programs written before, the data is in memory. Once the program runs out, the data is gone. I will use the data next time, but there is no data. Then what shall I do? Can you save all the data that have been computed and read them out and continue to use them the next time the program starts? In fact, to store data persistently, we need to store the data in memory on other persistent devices (hard disk, CD-ROM, U disk, etc.) besides memory.

When you need to store data in memory on a persistent device, this action is called an output (write) Output operation.

The action of reading data from a persistent device into memory is called an input (read) Input operation.

So we call this input and output action IO operation.


After a brief understanding of what IO is all about, the next step is to further understand the system.

In our operating system, the data is stored in the file, and the file is stored in the corresponding folder. So how do you describe this in Java?

 

1.2 The appearance of File classes

 

Open the API and search the File class. Read its description: An abstract representation of File files and directory pathnames. That is, in Java, files or directories (folders) are encapsulated as File objects. That is to say, if we want to manipulate the files on the hard disk, or folders, we just need to find the File class. So what functions do we have in File class to manipulate files or folders?

 

 

1.3 Constructor of File Class

 

 

 

 

 

We demonstrate how to create File objects by constructing methods:

public class FileDemo {
    public static void main(String[] args) {
        //File Demonstration of constructors
        String pathName = "e:\\java_code\\day22e\\hello.java";
        File f1 = new File(pathName);//take Test22 File encapsulation File Object. Note: Some can encapsulate files or folders that do not exist and become objects.
        System.out.println(f1);
        
        File f2 = new File("e:\\java_code\\day22e","hello.java");
        System.out.println(f2);
        
        //take parent Encapsulation file Object.
        File dir = new File("e:\\java_code\\day22e");
        File f3 = new File(dir,"hello.java");
        System.out.println(f3);
    }
}

1.4 Acquisition of File Classes

After the File object has been created, the File class has the following common methods to obtain file-related information

 

 

The method is demonstrated as follows:

public class FileMethodDemo {
    public static void main(String[] args) {
        //Create file objects
        File file = new File("Test22.java");
        //Get the absolute path of the file, that is, the full path
        String absPath = file.getAbsolutePath();
        //File The path of encapsulation is what we get.
        String path = file.getPath();
        //Get the file name
        String filename = file.getName();
        //Get file size
        long size = file.length();
        
        System.out.println("absPath="+absPath);
        System.out.println("path="+path);
        System.out.println("filename="+filename);
        System.out.println("size="+size);
    }
}

1.5 Creation and deletion of files and folders, etc.

Often mentioned above, we know that we can get the file name, file path (directory) and other information through File.

Next, we demonstrate how to create and delete files using File classes.

 

 

Let's demonstrate the method.

public class FileMethodDemo2 {
    public static void main(String[] args) throws IOException {
        // Operate on files or file additions.
        File file = new File("e:\\file.txt");
        // Create a file, if it does not exist, create true If the file exists, it is not created false.  If the path is wrong, IOException. 
        boolean b1 = file.createNewFile();
        System.out.println("b1=" + b1);
        //-----------Delete File Operation-------Note: Do not go to the recycling bin. Use caution------
         boolean b2 = file.delete();
         System.out.println("b2="+b2);

        //-----------Need to judge whether the file exists------------
         boolean b3 = file.exists();
         System.out.println("b3="+b3);

        //-----------Create, delete, and judge directory operations------------
        File dir = new File("e:\\abc");
        //mkdir()Create a single directory.//dir.mkdirs();Create multilevel directories
        boolean b4 = dir.mkdir();
        System.out.println("b4="+b4);
        //When deleting a directory, if there is something in the directory, it cannot be deleted directly.
        boolean b5 = dir.delete();
        //Only after the contents in the directory are deleted, ensure that the directory is empty. Then the directory can be deleted.
        System.out.println("b5=" + b5);

        //-----------Judge files, directories------------
        File f = new File("e:\\javahaha");// To determine whether it is a file or a directory, you must first determine whether it exists.
        // f.mkdir();//f.createNewFile();
        System.out.println(f.isFile());
        System.out.println(f.isDirectory());
    }
}

1.6 Introduction to listFiles() Method

 

Files are stored in directories (folders), so how to get all the files in a directory or folders in a directory? So let's first think that there may be more than one file or folder in a directory. If File has a function to get all the files and folders in a directory, then the result of the function is either an array or a collection. We started looking at the API.

 

The method is demonstrated as follows:

 

 

public class FileMethodDemo3 {
    public static void main(String[] args) {
        File dir = new File("e:\\java_code");
        //Gets the name of the current file and folder in the directory.
        String[] names = dir.list();
        for(String name : names){
            System.out.println(name);
        }
        //Get the current file and the file object in the directory, as long as you get the file object, then you can get the information you want.
        File[] files = dir.listFiles();
        for(File file : files){
            System.out.println(file);
        }
    }
}

 

Note: The following two conditions must be met when obtaining files or folders in a specified directory

1. The specified directory must exist.

2. The directory must be specified. Otherwise, it is easy to cause the return array to be null and NullPointerException to occur.

 

 

1.7 File Filter

 

With the listFiles() method, we can get all the files and folders in a directory, but can we filter them? For example, do we just want a file with a specified extension in a directory, or a folder with certain keywords?

We can first get all the files and folders in a directory, and traverse all the contents currently obtained. We are filtering in the traversal process, but this action is a bit troublesome. Java provides us with the corresponding functions to solve this problem.

Look up the API of the File class, find the listFiles method overloaded in the File class, and accept the specified filter.

 

 

 

 

 

Test class

public class FileDemo2 {
    public static void main(String[] args) {
        //Get the extension.java All documents
        //Establish File object
        File file = new File("E:\\code\\day11_code");
        //Gets the file with the specified extension,Because you want to filter all files for extensions, calling methods requires passing filters
        File[] files = file.listFiles(new MyFileFilter());
        //Traveling through all eligible documents
        for (File f : files) {
            System.out.println(f);
        }
    }
}

Custom class inherits FilenameFilter filter interface

//Define the class implementation file name FilenameFilter Filter
class MyFileFilter implements FilenameFilter{
    public boolean accept(File dir, String name) {
        return name.endsWith(".java");
    }
}

When looking up the API, we found that a FileFilter filter can also be accepted in listFiles(FileFilter filter). What's the difference between it and the FilenameFilter we talked about?

 

 

 

 

 

The accept method in the FilenameFilter filter accepts two parameters, one is the path of the current file or folder, and the other is the name of the current file or folder object.

The accept method in the FileFilter filter accepts a parameter for the current file or folder object

FilenameFilter can be used when we need to filter the name of the file. FileFilter can be used when we want to filter the current file or folder. For example, if we need all the folders in the current directory, FileFilter can be used.

Test class

public class FileDemo2 {
    public static void main(String[] args) {
        //Get the extension.java All documents
        //Establish File object
        File file = new File("E:\\code\\day11_code");
        //Gets the folder in the specified directory
        File[] files = file.listFiles(new FileFileterByDir());
        //Traveling through all eligible documents
        for (File f : files) {
            System.out.println(f);
        }
    }
}

Custom class inherits FileFilter filter interface

//File filter
class FileFileterByDir implements FileFilter{
    public boolean accept(File pathname) {
        return pathname.isDirectory();
    }
}

2. recursion

2.1 Overview of recursion

Recursion refers to the phenomenon of calling oneself within the current method

public void method(){
    System.out.println("Recursive demonstration");
    //Call yourself within the current method
    method();
}

Recursion is divided into two kinds, direct recursion and indirect recursion.

Direct recursion is called method calling itself. Indirect recursion can call method B by method A, method C by method B and method A by method C.

Recursive code demonstration, calculating the sum between 1-n, using recursive completion

public class DiGuiDemo {
    public static void main(String[] args) {
        //Calculate 1~num And, using recursive completion
        int n = 5;
        int sum = getSum(n);
        System.out.println(sum);
        
    }
    public static int getSum(int n) {
        if(n == 1){
            return 1;
        }
        return n + getSum(n-1);
    }
}

Code Execution Flow Diagram

Note: Recursion must be conditionally limited to ensure that recursion can stop, otherwise stack memory overflow will occur.

Although there are limited conditions in recursion, the number of recursions can not be too many. Otherwise, stack memory overflow will occur.

2.2 Recursive printing of file paths in all subdirectories

Write a method to print the file path in the specified directory and invoke the method

Requirement: If the specified directory has a subdirectory, print out the file path in the subdirectory.

Steps:

1. Specify the directory File object to print

2. Call the getFileAll() method

2.1 Gets all File objects in the specified directory

2.2 Traverse to get each File object

2.3 Determine whether the current File object is a directory

Determine the result to be true, specify as a directory, and call the getFileAll() method of step 2 again recursively

Decide that the result is false, indicating that it is a document, and the path to print the document

Code demo

public class FileDemo2 {
    public static void main(String[] args) {
        File file = new File("d:\\test");
        getFileAll(file);
    }
    //Gets all files in the specified directory and subdirectory
    public static void getFileAll(File file) {
        File[] files = file.listFiles();
        //Traverse through all files and folders in the current directory
        for (File f : files) {
            //Determine whether the current traversal is a directory
            if(f.isDirectory()){
                //It's a directory. Continue to get all the files and folders in this directory.
                getFileAll(f);
            }else{
                //Not a catalog, indicating the current f That's the file, so print it out.
                System.out.println(f);
            }
        }
    }
}

2.3 Search for. java files (including subdirectories) in a specified directory

Requirements: Print the specified directory, the file path of. java files in all subdirectories

Requirement: Write a method to print the. java file path in the specified directory and invoke the method

If the specified directory has subdirectories, print out the. java file path in the subdirectory

Steps:

1. Specify the directory File object to print

2. Call the getFileAll() method to pass in the directory File object to be printed

2.1 Gets all File objects of type. java in the specified directory through the FilenameFilter filter

2.2 Traverse to get each File object

2.3 Determine whether the current File object is a directory

Determine the result to be true, specify as a directory, and call the getFileAll() method of step 2 again recursively

Decide that the result is false, indicating that it is a document, and the path to print the document

2.4 Implementing Code Steps

Test class

public class FileDemo4 {
    public static void main(String[] args) {
        File file = new File("d:\\test");
        getFileAll(file);
    }
    //Gets all files in the specified directory and subdirectory
    public static void getFileAll(File file) {
        File[] files = file.listFiles(MyFileFilter());
        //Traverse through all files and folders in the current directory
        for (File f : files) {
            //Determine whether the current traversal is a directory
            if(f.isDirectory()){
                //It's a directory. Continue to get all the files and folders in this directory.
                getFileAll(f);
            }else{
                //Not a catalog, indicating the current f That's the file, so print it out.
                System.out.println(f);
            }
        }
    }
}

Custom class inherits FilenameFilter filter interface

//Define the class implementation file name FilenameFilter Filter
class MyFileFilter implements FilenameFilter{
    public boolean accept(File dir, String name) {
        return name.endsWith(".java");
    }
}

Tags: Java

Posted on Fri, 11 Oct 2019 01:47:48 -0700 by Funk001