02 | Java voice advanced | day08 | file class, recursion, comprehensive case (file filter)

Keywords: Java Lambda Windows Linux

Chapter 1 File class

1.1 overview

  1. (API) java.io.File class is an abstract representation of path names of files and directories. It is mainly used for creating, finding and deleting files and directories (representing folders).
    • Directory means folder
    • java encapsulates the files and folders (directories) in the computer as a File class. We can use the File class to operate the files and folders [!]
  2. We can use the method of File class
    • Create a file / folder
    • Delete files / folders
    • Get files / folders
    • Determine whether the file / folder exists
    • Traverse folders
    • Get file size
  • Note: the File class is a system independent class. Any operating system can use the methods in this class

  • [key]: remember these three words

    • File: file
    • Directory: folder / directory
    • Path: path

1.2 static member variable of file class

  1. path separator
    • windows – >; (semicolon)
    • linux – >: (colon)
  2. File path separator
    • windows – > \ (a backslash)
    • linux – > / (forward slash)
  3. Static member variable of File class
    • Representing the path
      • static String pathSeparator
        • System related path separator, which is represented as a string for convenience.
      • static char pathSeparatorChar
        • System related path separator.
    • Representing a file
      • static String separator
        • The system specific default name separator (file name separator), which is represented as a string for convenience.
      • static char separatorChar
        • The default name separator (file name separator) associated with the system.
  4. Code demonstration:
    public static void main(String[] args) {
        String pathSeparator = File.pathSeparator;
        System.out.println(pathSeparator);  //Printed; -- > Path separator,

        String separator = File.separator;
        System.out.println(separator);  //Print \ \

    }
  1. matters needing attention:
    • Operation path: the path cannot be written dead
        * c:\develop\a\a.txt  //windows
        * c:/develop/a/a.txt  //linux
        * "c:"+File.separator+"develop"+File.separator+"a"+File.separator+"a.txt"
    

1.3 absolute path and relative path

  • Route:
    1. Absolute path: a complete path
      • Path starting with drive letter (c:,D:)
            c:\\a.txt
            C:\\Users\itcast\\IdeaProjects\\shungyuan\\123.txt
            D:\\demo\\b.txt
        
    2. Relative path: a simplified path
      • Relative to the root directory of the current project (C:\Users\itcast\IdeaProjects\shungyuan)
      • If you use the root directory of the current project, the path can simplify writing
          C: \ \ users \ itcast \ \ ideaprojects \ \ shungyuan \ \ 123. TXT -- > simplify to: 123.txt (you can omit the root directory of the project)
      
  • Be careful:
    1. Path is case insensitive
    2. The file name separator in the path windows uses a backslash, which is an escape character. Two backslashes represent a common backslash

1.4 construction method of file class

  1. File(String pathname) -- > most used -- [!]
    • Create a new File instance [!] by converting the given pathname string to an abstract pathname
    1. Parameters:
      • ++String pathname + +: path name of string
      • Paths can end in files or folders
      • The path can be relative or absolute
      • The path can be existing or not
        • To create a File object, just encapsulate the string path as a File object, regardless of the true or false path [!]
  2. File(String parent, String child) -[!]
    • Create a new File instance based on the parent pathname string and the child pathname string.
    1. Parameter: divide the path into two parts
      • String parent: parent path
      • String child: subpath
    2. Benefits:
      • The parent path and child path can be written separately and used flexibly; both can be changed
  3. File(File parent, String child) -[!]
    • Create a new File instance based on the parent abstract pathname and the child pathname string.
    1. Parameter: divide the path into two parts
      • File parent: parent path
      • String child: subpath
    2. Benefits:
      • The parent path and child path can be written separately and used flexibly; both can be changed
      • The parent path is of File type. You can use the File method to perform some operations on the path [key points], and then use the path to create objects
    //Main method Demo02File.java
    public class Demo02File {
        public static void main(String[] args) {
            //show01();
    
            //show02("C:\\", "a.txt");  //C:\a.txt
            //show02("d:\\", "a.txt");    //d:\a.txt
            
            show03();   //c:\hello.java
        }
    
        //File(File parent, String child) construction method
        private static void show03() {
            File parent = new File("c:\\");
            File file = new File(parent, "hello.java");
            System.out.println(file);
        }
    
        //File(==String parent==, String child) construction method
        private static void show02(String parent, String child) {
            File file = new File(parent, child);
            System.out.println(file);
        }
    
        //File(String pathname) construction method
        private static void show01() {
            //End with file
            File f1 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\a.txt");
            //Overridden toString method
            System.out.println(f1); //E:\JavaWebApp\WorkSpace\oop\a.txt
    
            //End with folder
            File f2 = new File("E:\\JavaWebApp\\WorkSpace\\oop");
            //Overridden toString method
            System.out.println(f2); //E:\JavaWebApp\WorkSpace\oop
    
            //Relative path
            File f3 = new File("b.txt");
            //Overridden toString method
            System.out.println(f3); //b.txt
        }
    }

1.5 common methods of file class - Methods to obtain functions

  1. How to get the function of File class
    • public String getAbsolutePath()-[!]
      • Returns the absolute pathname string for this File.
      1. The path passed in the acquired construction method
      2. Whether the path is absolute or relative, the getAbsolutePath method returns an absolute path
    • public String getPath()-[!]
      • Convert this File to a pathname string.
      1. What is the path
      2. The getPath method is used to override the toString method
        • Source code:
            public String toString() {
                return getPath();
            }
        
    • public String getName()-[!]
      • Returns the name of the File or directory represented by this File.
      1. What we get is the end part (file / folder) of the construction method delivery path [!]
      2. Absolutely relative
    • public ++long++ length()-[!]
      • Returns the length of the File represented by this File.
      • Gets the size [!] of the file specified by the construction method, in bytes
      • Be careful:
        • There is no size concept for a folder. You cannot get the size of a folder
        • If the path given in the constructor does not exist, the length method returns 0
    public class Demo03File {
        public static void main(String[] args) {
            //show01();
            //show02();
            //show03();
            show04();
        }
    
        //public long ==length==()
        private static void show04() {
            //Existing files
            File f1 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\a.txt");
            long l1 = f1.length();
            System.out.println(l1);  //11 (bytes)
            //Files that do not exist
            File f2 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\b.txt");
            long l2 = f2.length();
            System.out.println(l2);  //0 (bytes)
            //Pass in a folder
            File f3 = new File("c:\\JavaWebApp");
            long l3 = f3.length();
            System.out.println(l3);  //0: folder has no size concept
        }
    
        //public String ==getName==()
        private static void show03() {
            //End of file
            File f1 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\a.txt");
            String absolutePath1 = f1.getName();
            System.out.println(absolutePath1);  //a.txt
            //End of folder
            File f2 = new File("E:\\JavaWebApp\\WorkSpace\\oop");
            String absolutePath2 = f2.getName();
            System.out.println(absolutePath2);  //oop
        }
    
        //public String ==getPath==()
        private static void show02() {
            //Absolute path
            File f1 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\a.txt");
            String absolutePath1 = f1.getPath();
            System.out.println(absolutePath1);  //E:\JavaWebApp\WorkSpace\oop\a.txt
            //Relative path
            File f2 = new File("a.txt");
            String absolutePath2 = f2.getPath();
            System.out.println(absolutePath2);  //a.txt
    
            System.out.println(f1); //E:\JavaWebApp\WorkSpace\oop\a.txt
            System.out.println(f1.toString());  //E:\JavaWebApp\WorkSpace\oop\a.txt
        }
    
        //public String ==getAbsolutePath==()
        private static void show01() {
            //Absolute path
            File f1 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\a.txt");
            String absolutePath1 = f1.getAbsolutePath();
            System.out.println(absolutePath1);  //E:\JavaWebApp\WorkSpace\oop\a.txt
            //Relative path
            File f2 = new File("a.txt");
            String absolutePath2 = f2.getAbsolutePath();
            System.out.println(absolutePath2);  //E:\JavaWebApp\WorkSpace\oop\a.txt
        }
    }

1.6 common methods of file class -- Methods of judging function

  1. The method of judging function of File class
    • public boolean exists()-[!]
      • Whether the File or directory represented by this File actually exists
      1. Used to determine whether the path in the construction method exists
        • Existence: true
        • Does not exist: false
    • public boolean isDirectory()-[!]
      • Whether this File represents a directory.
      1. Used to determine whether the path given in the constructor ends in a folder
        • Yes, true
        • No: false
    • public boolean isFile()-[!]
      • Whether this File represents a File.
      1. Used to determine whether the path given in the constructor ends in a file
        • Yes, true
        • No: false
  2. Notes on isDirectory and isFile methods:
    • There are only files / folders in the hard disk of the computer. The two methods are mutually exclusive
    • Both methods use the premise that the path must exist, otherwise both return false
    • Before using these two methods, you need to judge whether the path exists
        File f1 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\a.txt");
        if(f1.exists()){
            System.out.println(f1.isDirectory());   //false
            System.out.println(f1.isFile());   //true
        }
    
    public class Demo04File {
        public static void main(String[] args) {
            //show01();
            show02();
        }
    
        //public boolean ==isDirectory==()
        private static void show02() {
            File f1 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\a.txt");
            if(f1.exists()){
                System.out.println(f1.isDirectory());   //false
                System.out.println(f1.isFile());   //true
            }
    
            File f3 = new File("E:\\JavaWebApp\\WorkSpace\\oop");
            if(f3.exists()){
                System.out.println(f3.isDirectory());    //true
                System.out.println(f3.isFile());    //false
            }
        }
    
        //public boolean ==exists==()
        private static void show01() {
            //File path
            File f1 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\a.txt");
            System.out.println(f1.exists());    //true
            File f2 = new File("oop\\b.txt");   //Relative path
            System.out.println(f2.exists());    //false
            //Folder path
            File f3 = new File("E:\\JavaWebApp\\WorkSpace\\oop");
            System.out.println(f3.exists());    //true
        }
    }

1.7 common methods of file class - Method to create deletion function

  1. The method of File class to create delete function
    • public boolean createNewFile()-[!]
      • Create a new empty file if and only if the file with that name does not already exist.
      1. The path and name of the created file are given in the construction method (parameters of the construction method)
      2. Return value: Boolean
        • True: file does not exist, create file, return true
        • False: file exists, will not be created, return false
      3. Be careful:
        1. This method can only create files, not folders
          • "New folder" – > is a file: the type is not the name [!]
        2. The path to create the file must exist, otherwise an exception IOException will be thrown
        3. public boolean createNewFile() throws IOException
          • The createNewFile declaration throws an IOException. When we call this method, we must handle this exception, either throws or trycatch
    • public boolean delete()-[!]
      • Delete the File or directory represented by this File.
      1. This method can delete the file / folder given in the construction method path
      2. Return value: Boolean
        • True: file / folder deleted successfully, return true
        • False: if there is content in the folder, it will not be deleted and return false; the path in the construction method does not exist false
      3. Be careful:
        1. The delete method is to delete files / folders directly on the hard disk without going to the recycle bin. Be careful when deleting [key]
        2. Multi level folders cannot be deleted directly from the front
    • public boolean mkdir()-[!]
      • Create a directory represented by this File.
      1. Create a single level empty folder
    • public boolean mkdirs()-[!]
      • Create the directory represented by this File, including any required but nonexistent parent directories.
      1. You can create either single level empty folders or multi-level folders
  2. Similarities and differences between mkdir and mkdirs methods:
    • The path and name to create the folder are given in the construction method (parameters of the construction method)
      1. Return value: Boolean
        • True: folder does not exist, create folder, return true
        • False: the folder exists, will not be created, and returns false; the path given in the construction method does not exist, and returns false
      2. Be careful:
        1. This method can only create folders, not files
        • "New folder. txt" – > is a folder: the type does not depend on the name [!]
        1. The path to create the file can be nonexistent, no exception will be thrown, and the key will not be created without the path
    public class Demo05File {
        public static void main(String[] args) throws IOException {
            //show01();
            //show02();
            //show03();
        }
    
        //public boolean ==delete==()
        private static void show03() {
            //b.txt file deleted in absolute path
            File f1 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\b.txt");
            boolean d1 = f1.delete();
            System.out.println("d1:" + d1);
            //Deleted c.txt file in relative path
            File f2 = new File("c.txt");
            boolean d2 = f2.delete();
            System.out.println("d2:" + d2);
    
            //bbb file deleted in absolute path
            File f3 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\bbb");
            boolean d3 = f3.delete();
            System.out.println("d3:" + d3);
            //aaa files deleted in relative path (multilevel) - cannot be deleted
            File f4 = new File("aaa");
            boolean d4 = f4.delete();
            System.out.println("d4:" + d4); //false
        }
    
        //public boolean ==mkdir==()
        //public boolean ==mkdirs==()
        private static void show02() {
            //Create a bbb folder under absolute path
            File f1 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\bbb");
            boolean b1 = f1.mkdir();
            System.out.println("b1:" + b1); //b1:true
    
            //Create aaa\bbb\ccc\ddd folder multi level folder under relative path
            File f2 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\aaa\\bbb\\ccc\\ddd");
            boolean b2 = f2.mkdirs();
            System.out.println("b2:" + b2); //b1:true
    
        }
    
        //public boolean ==createNewFile==()
        private static void show01() throws IOException {
            //Create a b.txt file in absolute path
            File f1 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\b.txt");
            boolean b1 = f1.createNewFile();
            System.out.println("b1" + b1);  //true
            System.out.println(f1);
    
            //Create a c.txt file under the relative path
            File f2 = new File("c.txt");
            boolean b2 = f2.createNewFile();
            System.out.println("b2" + b2);  //true
            System.out.println(f2);
        }
    }

1.8 common method of file class traversal of directory (folder)

  1. File class traversal (folder) directory function
    • public String[] list()-[!]
      • Returns a String array representing all the sub files or directories in the File directory.
      1. Traversing the directory given in the construction method will get the names of all files / folders in the directory [!], and store the obtained names in an array of String type
      2. The list method prints the file / folder name regardless of absolute relative path
    • public File[] listFiles()-[!]
      • Returns an array of files representing all the sub files or directories in the File directory.
      1. Traversing the directory given in the construction method will obtain all the files / folders in the directory, encapsulate the files / folders as File objects [!], and store multiple File objects in the File array
      2. The absolute path of the listFiles method prints out the entire path of the file / folder name, while the relative path prints out the file / folder name
  2. Be careful:
    • The list method and listFiles method traverse the directories given in the construction method
    • If the path of the directory given in the constructor does not exist, a null pointer exception [!] will be thrown
    • If the path given in the constructor is not a directory, a null pointer exception [!] will also be thrown
    • Can traverse to hidden files and folders
    • The list method prints the file / folder name regardless of absolute relative path
    • The absolute path of the listFiles method prints out the entire path of the file / folder name, while the relative path prints out the file / folder name
    public class Demo06File {
        public static void main(String[] args) {
            show01();
            //show02();
        }
    
        //public File[] listFiles
        private static void show02() {
            File f1 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\Dark-horse-teaching");
            File[] arr = f1.listFiles();
            //Enhanced for printing (name of each file and folder)
            for (File f : arr) {
                System.out.println(f);
            }
        }
    
        //public String[] ==list==()
        private static void show01() {
            File f1 = new File("E:\\JavaWebApp\\WorkSpace\\oop\\Dark-horse-teaching");
            String[] arr = f1.list();
            //Enhanced for printing (name of each file and folder)
            for (String fileName : arr) {
                System.out.println(fileName);
            }
        }
    }
    
    //Results of show01():
    Dark-horse-teaching.iml
    pic
    src
    
    //Results of show02():
    E:\JavaWebApp\WorkSpace\oop\Dark-horse-teaching\Dark-horse-teaching.iml
    E:\JavaWebApp\WorkSpace\oop\Dark-horse-teaching\pic
    E:\JavaWebApp\WorkSpace\oop\Dark-horse-teaching\src

Chapter 2 recursion

2.1 overview

  1. Recursion: method calls itself
  2. Classification of recursion:
    • There are two kinds of recursion, direct recursion and indirect recursion.
    • Direct recursion is called method calling itself.
    • Indirect recursion can make method A call method B, method B call method C, and method C call method A.
  3. matters needing attention:
    • Recursion must be conditional to ensure that recursion can stop, or stack memory overflow will occur.
      • Note: when a method calls another method, the called method does not finish executing. The current method will wait for the called method to finish executing before continuing to execute
      • java.lang.StackOverflowError
    • Although there are restrictions in recursion, the number of recursions cannot be too many. Otherwise, stack memory overflow will occur
      • java.lang.StackOverflowError
    • Constructor, prohibit recursion
      • Compile and report errors: the construction method is used to create objects. Recursion always results in numerous objects in memory. Compile and report errors directly
  4. The premise of recursion:
    • When a method is called, the body of the method remains the same, and the parameters of each method call are different. Recursion can be used
    public class Demo01Recurison {
        public static void main(String[] args) {
            //a();
            b(1);
        }
    
        /*
            Constructor, prohibit recursion
                Compile and report errors
         */
        /*public Demo01Recurison() {
            Demo01Recurison();
        }*/
    
        //In recursion = = although there are restrictions = =, = = the number of recursions cannot be too many = =. Otherwise, stack memory overflow will occur
        //java.lang.StackOverflowError
        private static void b(int i) {
            System.out.println(i);
            if(i == 20000){
                return; //End method
            }
            b(++i);
        }
    
        //Recursion must be = = conditional limit = =, = = ensure recursion can stop = = down, otherwise stack memory overflow will occur.
        //java.lang.StackOverflowError
        private static void a() {
            System.out.println("a Method");
            a();
        }
    }

2.2 recursive summation

    public class Demo02Recurison {
        public static void main(String[] args) {
            int s = sum(3);
            System.out.println(s);
        }
    
        //Recursively calculating the sum of 1-n
        public static int sum (int n){
            //End of acquisition at 1:00
            if(n == 1){
                return 1;
            }
    
            //Get next added number
            return n + sum(n - 1);
        }
    }
  1. The principle of using recursion to calculate the sum of 1~n
  • Note:
    • Using recursive summation, main method calls sum method, sum method will always call sum method, resulting in multiple sum methods in memory (frequent creation method, call method, destroy method) - inefficient

2.3 recursive factorization

  • Factorial: the product of all positive integers less than or equal to the number
    public class Demo03Recurison {
        public static void main(String[] args) {
            int j = jc(5);
            System.out.println(j);
        }
    
        //Recursively calculating the sum of 1-n
        public static int jc (int n){
            //End of acquisition at 1:00
            if(n == 1){
                return 1;
            }
    
            //Get next multiplied number
            return n * jc(n - 1);
        }
    }
    
    //Result:
    120
  • Parameter variation of the method: 5,4,3,2,1

2.4 recursive printing of multi-level directory


2. demand:
Traverse the day08Test folder in the root directory of the project, and the subfolder of the day08Test folder, day08Test day08test \ a \ a.java day08Test \ a \ a.png day08Test \ abc.java day08Test \ abc.txt day08Test \ B day08Test \ B \ b.java day08Test \ B \ b.txt
3. Problems and solutions without recursion

    public class Demo04Recurison {
        public static void main(String[] args) {
            File file = new File("day08Test");
            getAllFile(file);
        }
    
        //The parameter passes the directory of File type, which is traversed in the method
        public static void getAllFile(File dir){
            System.out.println(dir);    //Print traversed directory
            File[] files = dir.listFiles();
            for (File f : files) {
                //Judge whether the file object f obtained by traversal is a folder
                if(f.isDirectory()){
                    //f is a folder, continue to traverse this folder
                    getAllFile(f);
                }else {
                    //f is the document, which can be printed directly
                    System.out.println(f);
                }
            }
        }
    }
    
    //Result:
    day08Test
    day08Test\a
    day08Test\a\a.JAVA
    day08Test\a\a.png
    day08Test\abc.java
    day08Test\abc.txt
    day08Test\b
    day08Test\b\b.java
    day08Test\b\b.txt

Chapter III comprehensive cases

3.1 file search


2. demand:
Traverse the day08Test folder in the root directory of the project, and the subfolder of the day08Test folder as long as the. Java ending file day08Test \ a day08Test \ a.java day08Test \ a \ a.png day08Test \ abc.java day08Test \ abc.txt day08Test \ B day08Test \ b.java day08Test \ B \ b.txt
3. analysis:
*2.4 do not move, just change the output
1. Convert File object f to string object (three ways)
* String name = f.getName();
* String name = f.getPath();
* String name = f.toString();
2. Call the method endsWith in the String class to determine whether the String ends in. java
* boolean b = name.endsWith(".java");
3. if statement, if it returns true at the end of. java, it will output

    public class Demo05Recurison {
        public static void main(String[] args) {
            File file = new File("day08Test");
            getAllFile(file);
        }
    
        //The parameter passes the directory of File type, which is traversed in the method
        public static void getAllFile(File dir){
            //System.out.println(dir); / / print the traversed directory
            File[] files = dir.listFiles();
            for (File f : files) {
                //Judge whether the file object f obtained by traversal is a folder
                if(f.isDirectory()){
                    //f is a folder, continue to traverse this folder
                    getAllFile(f);
                }else {
                    //f is the document, which can be printed directly
                    /*
                        day08Test\a\a.java
                        Just. java files
                        1. Convert File object f to string object
                        2. Call the method endsWith in the String class to determine whether the String ends in. java
                        3. if Statement, if it returns true at the end of. java, it will output
                     */
                    //String name = f.getName();
                    String name = f.getPath();
                    boolean b = name.endsWith(".java");
                    if(b){
                        System.out.println(f);
                    }
                }
            }
        }
    }
    
    //Result:
    day08Test\a\a.JAVA
    day08Test\abc.java
    day08Test\b\b.java

3.2 file filter optimization

  1. Demand:
        ergodic c:\\abc Folder,and abc Subfolders of a folder
        //Just. java end files
        c:\\abc
        c:\\abc\\abc.txt
        c:\\abc\\abc.java
        c:\\abc\\a
        c:\\abc\\a\\a.jpg
        c:\\abc\\a\\a.JAVA
        c:\\abc\\b
        c:\\abc\\b\\b.java
        c:\\abc\\b\\b.txt
    
  2. We can use filters to implement
  3. In the File class, there are two overloaded methods [key points] with ListFiles. The parameters of the methods pass the filter
    • File[] listFiles(FileFilter filter)
      • java.io.FileFilter interface: a filter for abstract pathnames (File objects).
      1. Function: used to filter files (File objects)
      2. Abstract methods: methods used to filter files
        • boolean accept(File pathname)
          • Tests whether the specified abstract pathname should be included in a pathname list.
        1. Parameters:
          • File pathname
            • Use the ListFiles method to traverse the directory to get each file object
    • File[] listFiles(FilenameFilter filter)
      • java.io.FilenameFilter interface: class instances that implement this interface can be used to filter filenames.
      1. Role: used to filter file names
      2. Abstract methods: methods used to filter files
        • boolean accept(File dir, String name)
          • Tests whether the specified file should be included in a file list.
          • The first parameter is the traversal directory
          • The second parameter is the name of the file in each directory [key]
        1. Parameters:
          1. File dir: the traversed directory passed in the constructor
          2. String name: use ListFiles method to traverse the directory and get the name of each file / folder
  4. Be careful:
    • There is no implementation class [!] for the two filter interfaces. We need to write our own implementation class [key], rewrite the filter method accept, and define the filter rules in the method

3.3 principle and use of filefilter

  1. Demand:
        ergodic c:\\abc Folder,and abc Subfolders of a folder
        //Just. java end files
        c:\\abc
        c:\\abc\\abc.txt
        c:\\abc\\abc.java
        c:\\abc\\a
        c:\\abc\\a\\a.jpg
        c:\\abc\\a\\a.JAVA
        c:\\abc\\b
        c:\\abc\\b\\b.java
        c:\\abc\\b\\b.txt
    
  2. Two things must be made clear
    1. Who called the accept method in the filter?
      • listFiles method
    2. What is the parameter pathname of the accept method?
      • The File + + object passed from listFiles [important - it's an object, so you need to convert the string before judging]++
  3. The listFiles method does three things:
    1. The listFiles method will traverse the directory passed in the construction method to get every File / folder in the directory – > encapsulated as a File object
    2. The listFiles method calls the method accept in the filter passed by the parameter
    3. The listFiles method will pass the parameter pathname of the accept method to each File object obtained through traversal
  4. In the implementation class of the FileFilter interface, the overridden accept method returns a Boolean value
    • true: the passed File object will be saved in the File array.
    • false: the passed File object will not be saved to the File array.
  5. Filter rules:
    • In the accept method, determine whether the File object ends in. java
      • Yes returns true
      • Not return false

    import java.io.File;
    import java.io.FileFilter;

    //Define an implementation class of FileFilter interface: FileFilterImpl.java
    //Override accept method
    public class FileFilterImpl implements FileFilter {

        @Override
        public boolean accept(File pathname) {
            /*
             * ==In the accept method = =, = = judge whether the File object ends in. java==
             * Yes returns true
             * Not return false
             */
            //If pathname is a folder, return true and continue to traverse the folder
            if(pathname.isDirectory()){
                return true;
            }else {
                return pathname.getName().toLowerCase().endsWith(".java");  //. toLowerCase() converts the upper case File object to lower case for judgment
            }
        }
    }
    
    import java.io.File;
    
    //Main method: Demo01Filter.java
    public class Demo01Filter {
        public static void main(String[] args) {
            File file = new File("day08Test");
            getAllFile(file);
        }
    
        //The parameter passes the directory of File type, which is traversed in the method
        public static void getAllFile(File dir){
            File[] files = dir.listFiles(new FileFilterImpl()); //Transfer filter objects
            for (File f : files) {
                //Judge whether the file object f obtained by traversal is a folder
                if(f.isDirectory()){
                    //f is a folder, continue to traverse this folder
                    getAllFile(f);
                }else {
                    //f is the document, which can be printed directly
                    System.out.println(f);
                }
            }
        }
    }
    
    //Result:
    day08Test\a\a.JAVA
    day08Test\abc.java
    day08Test\b\b.java

3.4 use of filenamefilter

  1. Note for the rewritten accept(File dir, String name) method:
    • The first parameter is: traversal directory
    • The second parameter is the name of the file in each directory
    1. Use steps:
      1. Encapsulate two parameters into a File object [!]
        • new File(dir, name)
        • The parent path is a directory
        • The subpath is the name of the file in the directory
      2. Example:
            //Pass filter object -- use anonymous inner class (of FilenameFilter interface)
            File[] files = dir.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    //Filter rule: pathname is the return of true at the end of folder or. java
                    return new File(dir, name).isDirectory() || name.toLowerCase().endsWith(".java");
                }
            });
        
    import java.io.File;
    import java.io.FileFilter;
    import java.io.FilenameFilter;

    //Main method: Demo02Filter.java
    public class Demo02Filter {
        public static void main(String[] args) {
            File file = new File("day08Test");
            getAllFile(file);
        }
    
        //The parameter passes the directory of File type, which is traversed in the method
        public static void getAllFile(File dir){
            //Pass filter object -- use anonymous inner class (of FileFilter interface)
            /*File[] files = dir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    //Filter rule: pathname is the return of true at the end of folder or. java
                    return pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".java");
                }
            });*/
            //Pass filter object -- use anonymous inner class (of FilenameFilter interface)
            File[] files = dir.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    //Filter rule: pathname is the return of true at the end of folder or. java
                    return new File(dir, name).isDirectory() || name.toLowerCase().endsWith(".java");
                }
            });
            for (File f : files) {
                //Judge whether the file object f obtained by traversal is a folder
                if(f.isDirectory()){
                    //f is a folder, continue to traverse this folder
                    getAllFile(f);
                }else {
                    //f is the document, which can be printed directly
                    System.out.println(f);
                }
            }
        }
    }
    
    //Result:
    day08Test\a\a.JAVA
    day08Test\abc.java
    day08Test\b\b.java

3.5 Lambda optimization program

  1. There is only one abstract method [emphasis] for either FileFiter or filenamefiler interface implementation class, so you can use Lambda expression [emphasis]
    import java.io.File;
    import java.io.FileFilter;
    import java.io.FilenameFilter;

    public class Demo02Filter {
        public static void main(String[] args) {
            File file = new File("day08Test");
            getAllFile(file);
        }
    
        //The parameter passes the directory of File type, which is traversed in the method
        public static void getAllFile(File dir){
            //Pass filter object -- use anonymous inner class (of FileFilter interface)
            /*File[] files = dir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    //Filter rule: pathname is the return of true at the end of folder or. java
                    return pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".java");
                }
            });*/
            //Pass filter object -- use anonymous inner class (of FilenameFilter interface)
            /*File[] files = dir.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    //Filter rule: pathname is the return of true at the end of folder or. java
                    return new File(dir, name).isDirectory() || name.toLowerCase().endsWith(".java");
                }
            });*/
    
            //These are anonymous inner classes
            //==================================================
            //Here is the Lambda expression - (of the FilenameFilter interface)
    
            ///Using Lambda expression to optimize anonymous inner class - (of FilenameFilter interface)
            /*File[] files = dir.listFiles((File d, String name)->{
                //Filter rule: pathname is the return of true at the end of folder or. java
                return new File(d, name).isDirectory() || name.toLowerCase().endsWith(".java");
            });*/
    
            ///Simplify Lambda expression - (of FilenameFilter interface)
            //Data types of multiple parameters can be omitted
            //When the method body is one line: {}, return,; to be omitted together
            //File[] files = dir.listFiles((d,  name)->new File(d, name).isDirectory() || name.toLowerCase().endsWith(".java"));
    
            //These are Lambda expressions - (of the FilenameFilter interface)
            //==================================================
            //Here is the Lambda expression - (of the FileFilter interface)
    
            //Using Lambda expression to optimize anonymous inner class - (of FileFilter interface)
            /*File[] files = dir.listFiles((File pathname) -> {
                return pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".java");
            });*/
    
            ///Simplify Lambda expression - (of FileFilter interface)
            //The data type of a parameter can be omitted, and the bracket can also be omitted
            //When the method body is one line: {}, return,; to be omitted together
            File[] files = dir.listFiles(pathname -> pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".java"));
    
            for (File f : files) {
                //Judge whether the file object f obtained by traversal is a folder
                if(f.isDirectory()){
                    //f is a folder, continue to traverse this folder
                    getAllFile(f);
                }else {
                    //f is the document, which can be printed directly
                    System.out.println(f);
                }
            }
        }
    }
    
    //Result:
    day08Test\a\a.JAVA
    day08Test\abc.java
    day08Test\b\b.java
Published 19 original articles, won praise 5, visited 316
Private letter follow

Posted by ym_chaitu on Fri, 06 Mar 2020 04:31:02 -0800