Review of java foundation -- File Class & recursion

catalogue

introduction

1, File class overview

1. Concept

2. Construction method  

3. Common methods

(1) . method enumeration

(2) Code demonstration (some common methods)

(3) . precautions

  2, File class map modeling

3, Recursion

1. What is recursion

2. Basic principle of recursion

3. Three elements of recursion

4, Graphics & code understanding recursion

1. Graphic modeling

  2. Code demonstration

5, Summary

introduction

If we are not afraid of being picked up by others, we will throw away a lot of things.         

——Wilde

Because of You (Kelly Clarkson)

                                                                (share a song list)

 

1, File class overview

1. Concept

1. Abstract representation of file and directory name path. File encapsulates not a real file, but a path name. It can exist or not exist. Later, we need to turn it into real existence through corresponding methods.

2. File class is mainly a class designed by JAVA for file operations (such as deletion, addition, etc.)

3. The package name of the File class is java.io, which implements two interfaces, serializable and comparable, so that its objects can be serialized and compared.

2. Construction method  

Create a new File instance with the given parent abstract pathname and child pathname string.

File(File parent, String child);

  Create a new File instance by converting the given pathname string to an abstract pathname.

File(String pathname) 

  Create a new File instance based on the parent pathname string and the child pathname string.

File(String parent, String child) 

  Create a new File instance by converting the given file: URI to an abstract pathname.

File(URI uri) 

  Code demonstration

/*
 - File Constructor for
 - */
 public static void main(String[] args) {
     //File(String pathname) converts the specified pathname into a file object
     File file = new File("D:\\1.txt");
     System.out.println(file);
     //File(String parent,String child) creates a file object according to the specified parent path and file path
     File file1 =  new File("D:\\a","1.txt");
     System.out.println(file1);
     //File(File parent,String child) creates a file object based on the specified parent path object and file path
     File parent = new File("D:\\a");
     File file2 = new File(parent, "1.txt");
     System.out.println(file2);
     File file3 = new File(new File("D:\\a"),"1.txt");
     System.out.println(file3);

 }

 

3. Common methods

(1) . method enumeration

Serial numberMethod description
1public String getName()
Returns the name of the file or directory represented by this abstract pathname.
2public String getParent(),
  Returns the pathname string of the parent pathname of this abstract pathname. If no parent directory is specified for this pathname, returns   null.
3public File getParentFile()
Returns the abstract pathname of the parent pathname of this abstract pathname. If this pathname does not specify a parent directory, returns   null.
4public String getPath()
Converts this abstract pathname to a pathname string.
5public boolean isAbsolute()
Test whether this abstract pathname is an absolute pathname.
6public String getAbsolutePath()
Returns the absolute pathname string of the abstract pathname.
7public boolean canRead()
Tests whether the application can read the file represented by this abstract pathname.
8public boolean canWrite()
Tests whether the application can modify the file represented by this abstract pathname.
9public boolean exists()
Tests whether the file or directory represented by this abstract pathname exists.
10public boolean isDirectory()
Tests whether the file represented by this abstract pathname is a directory.
11public boolean isFile()
Tests whether the file represented by this abstract pathname is a standard file.
12public long lastModified()
Returns the time when the file represented by this abstract pathname was last modified.
13public long length()
Returns the length of the file represented by this abstract pathname.
14public boolean createNewFile() throws IOException
If and only if there is no file with the name specified by this abstract pathname, a new empty file specified by this abstract pathname is created atomically.
15public boolean delete()
  Delete the file or directory represented by this abstract pathname.
16public void deleteOnExit()
When the virtual machine terminates, it is requested to delete the file or directory represented by this abstract pathname.
17public String[] list()
Returns a string array of the names of files and directories in the directory represented by this abstract pathname.
18public String[] list(FilenameFilter filter)
Returns a string array consisting of the names of the files and directories contained in the directory, which is represented by an abstract pathname that satisfies the specified filter.
19public File[] listFiles()
   Returns an array of abstract pathnames representing files in the directory represented by this abstract pathname.
20public File[] listFiles(FileFilter filter)
Returns an array of abstract pathnames representing the files and directories in the directory represented by this abstract pathname that satisfy a specific filter.
21public boolean mkdir()
Create the directory specified by this abstract pathname.
22public boolean mkdirs()
Create the directory specified by this abstract pathname, including creating a required but non-existent parent directory.
23public boolean renameTo(File dest)
  Rename the file represented by this abstract pathname.
24public boolean setLastModified(long time)
Sets the last modification time of the file or directory specified by this abstract pathname.
25public boolean setReadOnly()
Mark the file or directory specified by this abstract pathname so that it can be read only.
26public static File createTempFile(String prefix, String suffix, File directory) throws IOException
Creates a new empty file in the specified directory and generates its name using the given prefix and suffix string.
27public static File createTempFile(String prefix, String suffix) throws IOException
Create an empty file in the default temporary file directory and generate its name with the given prefix and suffix.
28public int compareTo(File pathname)
Compares two abstract pathnames alphabetically.
29public int compareTo(Object o)
Compares the abstract pathname with the given object alphabetically.
30public boolean equals(Object obj)
Tests whether this abstract pathname is equal to the given object.
31public String toString()
  Returns the pathname string for this abstract pathname.

(2) Code demonstration (some common methods)

Create file directory:

Method nameexplain
public boolean createNewFile()When a file with this name does not exist, a new empty file named by this abstract pathname is created
public boolean mkdir()Create a directory named after this abstract pathname
public boolean mkdirs()Create a directory named by this abstract pathname, including any required but nonexistent parent directory

  Example code:

public class FileDemo02 {
    public static void main(String[] args) throws IOException {
        //Requirement 1: I want to create a file java.txt in the E:\itcast directory
        File f1 = new File("E:\\itcast\\java.txt");
        System.out.println(f1.createNewFile());
        System.out.println("--------");

        //Requirement 2: I want to create a directory JavaSE under the E:\itcast directory
        File f2 = new File("E:\\itcast\\JavaSE");
        System.out.println(f2.mkdir());
        System.out.println("--------");

        //Requirement 3: I want to create a multi-level directory JavaWEB\HTML under the E:\itcast directory
        File f3 = new File("E:\\itcast\\JavaWEB\\HTML");
//        System.out.println(f3.mkdir());
        System.out.println(f3.mkdirs());
        System.out.println("--------");

        //Requirement 4: I want to create a file javase.txt in the E:\itcast directory
        File f4 = new File("E:\\itcast\\javase.txt");
//        System.out.println(f4.mkdir());
        System.out.println(f4.createNewFile());
    }
}

  Judgment function:

Method nameexplain
public boolean isDirectory()Test whether the File represented by this abstract pathname is a directory
public boolean isFile()Test whether the File represented by this abstract pathname is a File
public boolean exists()Test whether the File represented by this abstract pathname exists

Get features:

Method nameexplain
public String getAbsolutePath()Returns the absolute pathname string for this abstract pathname
public String getPath()Convert this abstract pathname to a pathname string
public String getName()Returns the name of the file or directory represented by this abstract pathname
public String[] list()Returns an array of name strings for files and directories in the directory represented by this abstract pathname
public File[] listFiles()Returns an array of File objects for files and directories in the directory represented by this abstract pathname

Example code:

public class FileDemo04 {
    public static void main(String[] args) {
        //Create a File object
        File f = new File("myFile\\java.txt");

//        public boolean isDirectory(): test whether the File represented by this abstract pathname is a directory
//        public boolean isFile(): test whether the File represented by this abstract pathname is a File
//        public boolean exists(): test whether the File represented by this abstract pathname exists
        System.out.println(f.isDirectory());
        System.out.println(f.isFile());
        System.out.println(f.exists());

//        public String getAbsolutePath(): returns the absolute pathname string of this abstract pathname
//        public String getPath(): converts this abstract path name to a path name string
//        public String getName(): returns the name of the file or directory represented by this abstract pathname
        System.out.println(f.getAbsolutePath());
        System.out.println(f.getPath());
        System.out.println(f.getName());
        System.out.println("--------");

//        public String[] list(): returns a string array of names of files and directories in the directory represented by this abstract pathname
//        public File[] listFiles(): returns the File object array of files and directories in the directory represented by this abstract pathname
        File f2 = new File("E:\\itcast");

        String[] strArray = f2.list();
        for(String str : strArray) {
            System.out.println(str);
        }
        System.out.println("--------");

        File[] fileArray = f2.listFiles();
        for(File file : fileArray) {
//            System.out.println(file);
//            System.out.println(file.getName());
            if(file.isFile()) {
                System.out.println(file.getName());
            }
        }
    }
}

  Delete function:

Method nameexplain
public boolean delete()Delete the file or directory represented by this abstract pathname

Example code:

public class FileDemo03 {
    public static void main(String[] args) throws IOException {
//        File f1 = new File("E:\\itcast\\java.txt");
        //Requirement 1: create a java.txt file in the current module directory
        File f1 = new File("myFile\\java.txt");
//        System.out.println(f1.createNewFile());

        //Requirement 2: delete the java.txt file in the current module directory
        System.out.println(f1.delete());
        System.out.println("--------");

        //Requirement 3: create itcast directory under the current module directory
        File f2 = new File("myFile\\itcast");
//        System.out.println(f2.mkdir());

        //Requirement 4: delete the itcast directory under the current module directory
        System.out.println(f2.delete());
        System.out.println("--------");

        //Requirement 5: create a directory itcast under the current module, and then create a file java.txt in this directory
        File f3 = new File("myFile\\itcast");
//        System.out.println(f3.mkdir());
        File f4 = new File("myFile\\itcast\\java.txt");
//        System.out.println(f4.createNewFile());

        //Requirement 6: delete the directory itcast under the current module
        System.out.println(f4.delete());
        System.out.println(f3.delete());
    }
}

(3) . precautions

The difference between absolute path and relative path:

  • Absolute path: the full path name. You can locate the file it represents without any other information. For example: E:\itcast\java.txt

  • Relative path: must be interpreted using information from other path names. For example: myFile\java.txt

 

  2, File class map modeling

When talking about File class, I can't avoid IO stream, which is certain. If you don't have a system concept, it will be messy. Please see the following:

  I'll introduce the IO stream system in several chapters. It's too much for everyone to look at.

 

3, Recursion

Recursion has an algorithm, data structure, do not know, it is recommended to review the following here.

1. What is recursion

The so-called recursion, in mathematics and computer science, refers to the algorithm of using the function itself in the definition of the function. Generally speaking, the essence of recursive algorithm is to decompose the problem into subproblems of similar problems with reduced scale, and then recursively call methods to represent the solution of the problem.

2. Basic principle of recursion

First, each level of function call has its own variables.

Second, each function call will return once.

Third, in recursive functions, the statements before recursive calls have the same execution order as the called functions at all levels.

Fourth, in a recursive function, the execution order of the statements after the recursive call is opposite to that of each called function.

Fifth, although each level of recursion has its own variables, the function code will not be copied.


3. Three elements of recursion

Element 1: define what you want to do with this function. No matter what the code in the function is, you should first understand what the function of your function is and what kind of thing you want to accomplish.

The second element: find the recursive end condition. We need to find out what the parameter is, the recursion ends, and then directly return the result. Please note that at this time, we must be able to directly know the result of the function according to the value of the parameter.

The third element: find out the equivalent relationship of the function. We should constantly narrow the range of parameters. After narrowing, we can make the result of the original function unchanged through some auxiliary variables or operations.

 

4, Graphics & code understanding recursion

1. Graphic modeling

 

 

  2. Code demonstration

public class Digui {

    public static int Zuhe1(int n,int k){
        int x=1,y=1,z=1,c;
        for(int i=n;i>0;i--){
            x=i*x;
        }
        for(int i=k;i>0;i--){
            y=i*y;
        }
        for(int i=n-k;i>0;i--){
            z=i*z;
        }
        c=x/(y*z);
        return c;
    }//Formula method
    public static int Zuhe2(int n,int k){
         int c=1;
         for(int i=k;i<n;i++){
             c=c*(i+1)/(i-k+1);
         }
         return c;
    }//Recursive method
    public static int Zuhe3(int n,int k){
        int i=n;
        if(n==k){
            return 1;
        }
        else{
            return Zuhe3(n-1,k)*n/(n-k);
        }
        
    }//Recursive method

    public static void main(String args[]) {
    int n,k;
    Scanner sc=new Scanner(System.in);
    n=sc.nextInt();
    k=sc.nextInt();
    System.out.println(Zuhe1(n,k));
    System.out.println(Zuhe2(n,k));
    System.out.println(Zuhe3(n,k));
    }
}

//Operation results
6
4
15
15
15

 

5, Summary

 

 

Point a praise, comment and collect

Tags: Java Back-end

Posted on Wed, 10 Nov 2021 21:16:41 -0500 by Jacquelyn L. Ja