Java USES the File class to traverse directories and file instance code

  • 2020-07-21 07:40:29
  • OfStack

1. Constructor


File(String args0)// use 1 Creates a string representing a path to a file or directory 1 a File object 
File(URL args0)// use 1 a URL Object creation File object 
File(File args0, String args1)// use 1 a File object (1 Is a directory ) and 1 A string of filenames was created File object 
File(String args0, String args1)// use 1 The directory string and 1 Creates an object with a string of filenames 

There are two things to note about using the File class:

First, the File class is used to represent the name, size, and other information of a file or directory and cannot be used to access the contents of a file.

Second, backslashes or double slashes should be replaced in the path of argument passing.

2. Common methods


exists()// Determines whether the current file or directory exists 

mkdir()// Create a single level directory, you cannot create multiple levels of directories 
mkdirs()// Create multilevel directories 
createNewFile()// To create a file with the current path, you need to throw an exception if the path does not exist 

delete()// Deletes the current directory or file 

isDirectory()// Determine the current File Object directory 
isFile()// Determine the current File Whether the object 1 A file 

getAbsolutePath()// Returns the absolute path to the current directory or file 
getName()// Returns the name of the current directory or file 
getParent()// Returns the parent path of the current directory or file 

list()// return 1 a String An array of subdirectories and files under the current directory, not including files or directories under the subdirectory 
listFiles()// return 1 a File An array of subdirectories and files under the current directory, not including files or directories under the subdirectory 

Example 3.

Traverse the directory, printing all directories at all levels.


import java.io.File;
import java.io.IOException;

public class FileTest {

  public static void main(String[] args) {
    File dir = new File("F:/documents/example");
    listDirectory(dir);
  }
  
  public static void listDirectory(File dir) {
    if (!dir.exists()) {
      throw new IllegalArgumentException(" directory " + dir + " There is no ");
    }
    if (!dir.isDirectory()) {
      throw new IllegalArgumentException(dir + " Not a directory ");
    }
    File[] files = dir.listFiles();
    if (files != null && files.length > 0) {
      for (File file : files) {
        if (file.isDirectory()) {
          listDirectory(file);
        } else {
          System.out.println(file);
        }
      }
    }
  }

}


Related articles: