JAVA files and recursion

catalogue

1. File class

java.io.File class is an abstract representation of file and directory pathnames. It is mainly used for the creation, search and deletion of files and directories.

1.1 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.

Code example:

// File pathname
String pathname = "D:\\aaa.txt";
File file1 = new File(pathname);
// File pathname
String pathname2 = "D:\\aaa\\bbb.txt";
File file2 = new File(pathname2);
// Pass parent and child path strings
String parent = "d:\\aaa";
String child = "bbb.txt";
File file3 = new File(parent, child);
// Through the parent File object and child path string
File parentDir = new File("d:\\aaa");
String child = "bbb.txt";
File file4 = new File(parentDir, child);

be careful:

  1. A File object represents a File or directory that actually exists in the hard disk.
  2. Whether there is a File or directory in this path does not affect the creation of the File object.

1.2 common methods

1.2.1 method of obtaining document information

  • public String getAbsolutePath(): returns the absolute pathname string of this File.
  • public String getPath(): convert this File to the pathname string provided when creating the File.
  • 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.

Code example:

public static void main(String[] args) {
    File f = new File("d:/aaa/bbb.java");
    System.out.println("File absolute path:"+f.getAbsolutePath());
    //Returns the pathname string provided when constructing the file
    //Returned when f = new file (". / aaa/bbb.java")/ aaa/bbb.java
    System.out.println("File construction path:"+f.getPath());
    System.out.println("File name:"+f.getName());
    System.out.println("file length:"+f.length()+"byte");
    File f2 = new File("d:/aaa");
    System.out.println("Directory absolute path:"+f2.getAbsolutePath());
    System.out.println("Directory construction path:"+f2.getPath());
    System.out.println("Directory name:"+f2.getName());
    System.out.println("Directory length:"+f2.length());
}
Output result:
File absolute path:d:\aaa\bbb.java
 File construction path:d:\aaa\bbb.java
 File name:bbb.java
 file length:636 byte
 Directory absolute path:d:\aaa
 Directory construction path:d:\aaa
 Directory name:aaa

API Description: length(), indicating the length of the File. However, if the File object represents a directory, the return value is not specified.

1.2.2 document judgment method

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

Code example:

public static void main(String[] args) {
    File f = new File("d:\\aaa\\bbb.java");
    File f2 = new File("d:\\aaa");
    // Judge whether it exists
    System.out.println("d:\\aaa\\bbb.java Does it exist:"+f.exists());
    System.out.println("d:\\aaa Does it exist:"+f2.exists());
    // Determine whether it is a file or directory
    System.out.println("d:\\aaa file?:"+f2.isFile());
    System.out.println("d:\\aaa catalogue?:"+f2.isDirectory());
}
Output result:
d:\aaa\bbb.java Does it exist:true
d:\aaa Does it exist:true
d:\aaa It's a file?:false
d:\aaa It's a directory?:true

1.2.3 method of operating documents

  • public boolean createNewFile(): creates a new empty file if and only if the file with this name does not exist yet.
  • public boolean delete(): delete 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.

Code example:

public static void main(String[] args) throws IOException {
    // File creation
    File f = new File("aaa.txt");
    System.out.println("Does it exist:"+f.exists()); // false
    System.out.println("Create:"+f.createNewFile()); // true
    System.out.println("Does it exist:"+f.exists()); // true
    // Directory creation
    File f2= new File("newDir");
    System.out.println("Does it exist:"+f2.exists());// false
    System.out.println("Create:"+f2.mkdir()); // true
    System.out.println("Does it exist:"+f2.exists());// true
    // Create multi-level directory
    File f3= new File("newDira\\newDirb");
    System.out.println(f3.mkdir());// false, mkdirs for multi-level directory
    File f4= new File("newDira\\newDirb");
    System.out.println(f4.mkdirs());// true
    // Deletion of files
    System.out.println(f.delete());// true
    // Deletion of directory
    System.out.println(f2.delete());// true
    System.out.println(f4.delete());// false, the directory must be empty
}

1.3 absolute path and relative path

  • Absolute path: the path starting from the drive letter. This is a complete path.
  • Relative path: relative to the path of the project directory, this is a convenient path, which is often used in development.

Code example:

public static void main(String[] args) {
    // BBB under disk D Java file
    File f = new File("D:\\bbb.java");
    System.out.println(f.getAbsolutePath());
    // BBB under Project Java file
    File f2 = new File("bbb.java");
    System.out.println(f2.getAbsolutePath());
}

Output result:
D:\bbb.java
D:\myproject\bbb.java

2. Recursion

2.1 general

There are two kinds of recursion, direct recursion and indirect recursion.

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

Precautions for using recursion:

  • 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. Recursion is prohibited.

2.2 recursive printing of multi-level directories

When printing multi-level directories of files, we generally need to use recursive implementation.

Code example:

//Recursive Method 
public static void printDir(File dir) {
    // Get sub files and directories
    File[] files = dir.listFiles();
    // Cyclic printing
    for (File file : files) {
        // judge
        if (file.isFile()) {
            // Is the absolute path of the output file
            System.out.println("file name:"+ file.getAbsolutePath());
        } else {
            // Is the directory, and the absolute path of the output directory
            System.out.println("catalogue:"+file.getAbsolutePath());
            // Continue to traverse and call printDir to form recursion
            printDir(file);
        }
    }
}

2.3 recursive search for files

When we are looking for all suffixes under a directory java files, you can use recursive implementation.

Code example:

public static void printDir(File dir) {
    // Get sub files and directories
    File[] files = dir.listFiles();
    // Cyclic printing
    for (File file : files) {
        if (file.isFile()) {
            // Is a file. Judge the file name and output the absolute path of the file
            if (file.getName().endsWith(".java")) {
                System.out.println("file name:" + file.getAbsolutePath());
            }
        } else {
            // It is a directory. Continue to traverse to form recursion
            printDir(file);
        }
	}
}

3. Document filter

java.io.FileFilter is an interface, which is the filter of File. The object of this interface can be passed to listFiles(FileFilter) of the File class as a parameter. There is only one method in the FileFilter interface:

boolean accept(File pathname): the parameter is File, which indicates all sub files and subdirectories under the current File. If it is retained, it returns true; if it is filtered out, it returns false.

Let's take the above file search as an example to filter out the non - documents java for the suffix file, and then print all java file.

Code example:

public static void printDir2(File dir) {
    // Create filter subclass objects by anonymous inner class
    File[] files = dir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.getName().endsWith(".java")||pathname.isDirectory();
        }
    });
    // Cycle through all java file
    for (File file : files) {
        if (file.isFile()) {
            System.out.println("file name:" + file.getAbsolutePath());
        } else {
            printDir2(file);
        }
    }
}

Tags: Java

Posted by andre_c on Sat, 07 May 2022 23:39:35 +0300