Java advanced File, recursion, File filter

catalogue

File

recursion

File filter

File

It is an abstract representation of file and directory path names. It is mainly used for the creation, search and deletion of files and directories.

Static properties

  • static String pathSeparator path separator related to the system: windows: semicolon ';' linux: colon ':'
  • static String separator system related file name separator: windows: backslash '\' linux: forward slash '/'

The operation path should not be written dead, for example: "C:" + file separator+"a.text"

Construction method

  • public File(String pathname): create a new File instance by converting the given pathname string to an abstract pathname.
  • public File(String parent, String child): creates a new File instance from the parent pathname string and the child pathname string.
  • public File(File parent, String child): creates a new File instance from the parent abstract pathname and child pathname strings.

pathname attribute, regardless of the authenticity of the path

Acquisition method

  • public String getAbsolutePath(): returns the absolute pathname string of this File.
  • public String getPath(): convert this File into a pathname string (the argument passed in by the constructor).
  • public String getName(): returns the name of the File or directory represented by this File.
  • public long length(): returns the length of the File represented by this File, in bytes. If the folder size cannot be obtained, the path does not exist and the folder acquisition length returns 0

Note: the toString method of File class actually calls getPath()

Judgment function method

  • public boolean exists(): whether the File or directory represented by this File actually exists.
  • public boolean isDirectory(): whether this File indicates a directory.
  • public boolean isFile(): this File indicates whether it is a File.

isDirectory() and isFile() are mutually exclusive because there are only two formats of files and folders in the system

Create and delete function methods

  • public boolean createNewFile(): creates a new empty file if and only if the file with this name does not exist yet.
  • public boolean delete(): deletes the File or directory represented by this File.
  • public boolean mkdir(): create the directory represented by this File.
  • public boolean mkdirs(): create the directory represented by this File, including any required but nonexistent parent directory.

Directory traversal method

  • public String[] list(): returns a String array representing all sub files or directories in the File directory.
  • public File[] listFiles(): returns a File array representing all sub files or directories in the File directory.

If the directory path given in the construction method does not exist and the path given in the construction method is not a directory, a null pointer exception will be thrown

Example method

  public static void main(String[] args) {
        //Create File object
        File file1 = new File("D:" + File.separator + "TEST001" + File.separator + "a.txt");//D:\TEST001\a.txt
        File file2 = new File("D:" + File.separator + "TEST001" + File.separator , "b");
        File file3 = new File("D:" + File.separator + "TEST001" + File.separator + "a");
        File file4 = new File("D:" + File.separator + "TEST001" + File.separator + "b"+File.separator+"q.java");
        System.out.println("file1 Does it exist?"+file1.exists());//false
        try {
            //Create files, folders
            file1.createNewFile();
            file2.createNewFile();
            file3.mkdir();//Single stage path
            file4.mkdirs();//Multilevel paths create multilevel folders
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("file1 Does it exist?"+file1.exists());//true
        System.out.println(file1.getAbsolutePath());//Absolute path D:\TEST001\a.txt
        System.out.println(file1.getName());//File name a.txt
        System.out.println("file1 Is it a file:"+file1.isFile());//true
        file1.delete();//delete
        System.out.println("file1 Does it exist?"+file1.exists());//false
    }

recursion

Refers to the phenomenon of calling itself within the current method

Recursive classification:

  • Direct recursion: call yourself
  • Indirect recursion: A calls B, B calls C, and C calls A

matters needing attention:

  • Recursion must be conditionally limited to ensure that recursion can stop, otherwise stack memory overflow will occur
  • Although there are restrictions in recursion, the number of recursions cannot be too many. Otherwise, stack memory overflow will also occur.
  • Construction method, prohibit recursion (otherwise many objects will be created)

Causes of stack overflow caused by recursion

The a method has no conditions, so it can't stop, which will cause stack memory overflow

Case: recursive summation

 public static void main(String[] args) {
        System.out.println(sum(3));
    }
    private static int sum(int num) {
        if(num==1){
            return 1;//Stop program given qualification
        }
        return num+sum(num-1);
    }

Principle: code goes in layer by layer, and data comes out layer by layer from the inside to the outside

Case: traversing multi-level folders and files

 private static void getdirs(File file) {
        File[] files = file.listFiles();//Get directory
        for (File file1 : files) {
            if(file1.isDirectory()){//Determine whether there are subdirectories
                getdirs(file1);//If yes, continue to traverse the directory (recursion)
            }else{
                System.out.println(file1);//If no information is printed directly
            }
        }
    }

File filter

You can pass in filters in listFiles (2 types)

  • Filefilter: override boolean accept(File pathname)
  • Filenamefilter: override boolean accept(File dir, String name)

pathname is the File object obtained by traversing the directory using listFilter {true: keep the object} false: delete the object

Name: file name

Sample code (implemented through lambda expressions)

 private static void getdirs(File file) {
//        File[] files = file. listFiles((path) -> path. getName(). endsWith(".docx")||path. isDirectory());// The file name starts with Return true at the end of docx or folder
        File[] files = file.listFiles((path, name) -> new File(path, name).isDirectory() || name.endsWith(".docx"));
        for (File file1 : files) {
            if(file1.isDirectory()){//Determine whether there are subdirectories
                getdirs(file1);//If yes, continue to traverse the directory (recursion)
            }else{
                System.out.println(file1);//If no information is printed directly
            }
        }
    }

Keywords: Java

Added by simonp on Sat, 18 Dec 2021 06:55:39 +0200