当前位置:网站首页>Construction methods of file class and various common methods

Construction methods of file class and various common methods

2022-06-21 06:49:00 naoguaziteng

Objective record

1.File class

2. Construction method

3.File Methods in class

4. File name filter (FilenameFilter)

5. Related cases

Judge D Do you have a suffix of .jpg The file of , If there is , Just output the file name .

Recursively delete non empty folders ( Catalog ).


1.File class

File Class is an abstract representation of file and directory pathnames . And this File Class can be used to encapsulate files , It can also be used to encapsulate directories ., And then operate on it !

2. Construction method

  • File(String pathname):                    According to a path, we get File object    
  • File(String parent, String child):         According to a directory and a sub file / The directory gets File object
  • File(File parent, String child):             According to a father File Object and a sub file / The directory gets File object

3.File Methods in class

  • createNewFile()              Create a new file If there is such a file , We won't create .
  • mkdir()                            Create folder If there is such a folder , We won't create Note that this method can only create a single-layer Directory If you create a multi-layer directory, you have to create it layer by layer
  • mkdirs()                          Create folder , If the parent folder does not exist , It will help you create You can create multi tier directories Of course, you can also create a single-layer Directory
  • delete()                            Delete files or folders ( The folder can only be deleted if it is empty ! If there are files in this folder , You can't delete it ! Be careful :Java Delete in does not go to the recycle bin . To delete a folder , This folder cannot contain files or folders )
  • renameTo(File dest)       Rename the file to the specified file path ( If the pathnames are the same , Will be renamed . If the pathnames are different , It's changing the name and cutting .)
  • isDirectory()                   Determine if it's a directory
  • isFile()                              Determine if it's a document
  • exists()                            Judge whether it exists
  • canRead()                        Judge whether it is readable
  • canWrite()                        Judge whether it is writable
  • isHidden()                        Determine whether to hide
  • isAbsolute()                    Determine whether the absolute path is used
  • getAbsolutePath()          Get absolute path
  • getParent()                      Returns the pathname string of the parent directory of this abstract pathname , If no parent directory is specified for this pathname , Then return to null.
  • getParentFile()                Returns the abstract pathname of the parent directory of this abstract pathname , If no parent directory is specified for this pathname , Then return to null.
  • getTotalSpace()               Returns the partition size specified by this abstract pathname . Return total capacity Unit byte  
  • getFreeSpace()                Returns the number of unallocated bytes in the partition specified by this abstract pathname . Return remaining capacity Unit byte
  • getName()                        Get the name
  • length()                            To obtain the length of the . That's file size , How many bytes are there
  • lastModified()                  Get the last modification time , The unit is millisecond
  • list()                                  Get the names of all files or folders in the specified directory , Then put the string array
  • listFiles()                          Get all the files or folders in the specified directory , And then put in File Array  

matters needing attention : If you create a file or folder and forget to write the drive path , that , Default under project path

Add :   A relative path is a path without a drive letter . The corresponding absolute path is the path with the drive letter

4. File name filter (FilenameFilter)

  • public String[] list(FilenameFilter filter)
  • public File[] listFiles(FilenameFilter filter)            After use , You will only get the content that needs to be filtered out

5. Related cases

  • Judge D Do you have a suffix of .jpg The file of , If there is , Just output the file name .

import java.io.File;
import java.io.FilenameFilter;

public class Test {
    public static void main(String[] args) {
       /* A:
         Case presentation :
         demand : Judge E Do you have a suffix of .jpg The file of , If there is , Just output the file name */

            File file = new File("D:\\test");              // Encapsulate folders test
            File[] files = file.listFiles();               // Save all the files and folders in the folder into the file array 
        // Method 1 
        for (File f : files) {
            if (f.isFile() && f.getName().endsWith(".jpg")) {
                System.out.println(f.getName());
            }
        }
          

        // Method 2 
            File[] files1 = file.listFiles(new FilenameFilter() {    // filter 
                // Method overridden in filter 
                @Override
                public boolean accept(File parent, String name) {     // Parent path , Sub file name 
                    File file1 = new File(parent, name);              // Override the parent path , The sub file name encapsulates 
                    return file1.isFile() && file1.getName().endsWith(".jpg");
                }
            });
            // The filtered file array files1 There are only .jpg Final document 
            //for Loop output file name 
            for (File file1 : files1) {
                System.out.println(file1.getName());
            }
        }
    }

  • Recursively delete non empty folders ( Catalog ).

import java.io.File;

public class DeleteTest {
    public static void main(String[] args) {
        // Programming , Delete   Specify... In the directory   All files and folders   ( Include subfolders )
        File file=new File("D:\\test"); 
        deleteDir(file);         // Delete folder method 
    }

    private static void deleteDir(File file) {
        File[] files = file.listFiles();       // Put all the objects in the folder into 
        for (File f : files) {
            if (f.isFile()){
                f.delete();                    // Delete file 
            }
            if (f.isDirectory()){
                deleteDir(f);                  // If it's a non empty folder , recursive 
                f.delete();                    // Delete empty folder 
            }
        }
        file.delete();                         // Delete the last folder . For example, in this example test Folder 
    }
}

( Xiaobian is also trying to learn more ! I'll share it later !)

Hope to be helpful to friends !!!!

  

原网站

版权声明
本文为[naoguaziteng]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210624100063.html