[Java] section thirty-fifth the File class

File class for files \ folders of various operations: create, delete, modify the name to view a variety of information, a variety of judgment
File can create, delete, rename files and directories, but can not access the file File content itself. If you need to access the contents of the file itself, you need to use input / output streams.

Three File class constructor:

  • public File(String pathname)
  • public File(String parent,String child)
  • public File(File parent,String child)

Common method of the File class:

Only for file / folder, if it comes to reading and writing files or modify the contents, need to use IO streams.

  • getAbsolutePath (): Gets the absolute path;
  • getAbsoluteFile (): Gets the absolute path;
  • getPath (): get the relative path;
  • getName (): Gets the file name;
  • getParent (): Get on a path;
  • length (): Gets file size;
  • lastModified (): Gets the last modified date of the file;
  • list (): Gets the name of an array of the specified directory for all files / folders
  • listFiles (): Gets an array of File specified directory for all files / folders
  • a.renameTo (b): a must be present, b allowed to exist, can play a role in moving a file / folder
  • isFile (): Whether the file;
  • isDirectory (): whether it is a folder;
  • canRead (): is readable;
  • canWrite (): is writable;
  • isHidden (): whether to hide;
  • exists (): if there is;
  • createNewFile (): create a new file, if present, is not created, return false;
  • delete (): delete the file / folder empty;
  • mkdirs (): create folders, together with the upper did not create;
  • mkdir (): create a folder, there is no upper or create;

Example:

Is there a file with an .exe suffix judgment under specified directory, if there is, the output file name

package cn.jingpengchong.file;

import java.io.File;

public class Test {

    public static void main(String[] args) {
        File file = new File("D:\\baidu\\Baidu");
        select(file);
    }

    public static void select(File file){
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            if(files[i].isDirectory()){
                select(files[i]);
            }else{
                if(files[i].getName().endsWith(".exe")){
                    System.out.println(files[i].getName());
                }
            }
        }
    }
}

Results are as follows:
Here Insert Picture Description

Published 128 original articles · won praise 17 · views 2746

Guess you like

Origin blog.csdn.net/qq_43705275/article/details/103988044