JAVA File class (file traversal, creation, deletion)

 

File class constructor

	File f1=new File("H://asc//");//The path of incoming file/directory
		File f2=new File(f1,"test.txt");//The first parameter is a directory file, and the second parameter is the file to be created in the current f1 directory
	
		

 

file.list(); Get a string array of all files/directories under the file folder

	String []liStrings=f1.list();
		for (int i = 0; i < liStrings.length; i++) {
			System.out.println(liStrings[i]);
		}
		
	 

Use the list() function to traverse the folder and recursively display the files/folders under the folder

public static void dfs(String filename) { // The first letter of the case-sensitive String class in java is capitalized

		File f = new File(filename);
		String namelist[] = f.list();
		for (int i = 0; i < namelist.length; i++) {
			File fchild = new File(filename + "/" + namelist[i]);
			for (int j = 0; j < deep; j++)
				System.out.print("   ");
			if (!fchild.isDirectory())
				System.out.println(namelist[i]);// file printing
			else {// directory
				System.out.println(namelist[i] + "/");// First print and then recursively call itself
				dfs(filename + "/" + namelist[i]);
			}
		}
	}

  

 

 

file.isFile() determines whether the current file is a file file.isDirectory() is a directory file.exist(); whether the file or directory exists

		File f1=new File("H://asc//");//
		File f2=new File(f1,"test.txt");//
		File f3=new File("H://notexistdir");
//	
		System.out.println(f1.isFile());
		System.out.println(f2.isFile());
		System.out.println(f3.isFile());
		
		System.out.println(f1.isDirectory());
		System.out.println(f2.isDirectory());
		
		System.out.println(f3.exists()); 
 //Run result:
false
true
false
true
false
false

  

  

File/directory creation, deletion

The function file.createNewFile() creates this File object file. If the file already exists, createNewFile returns fasle Failed to create the file

The function file.mkdir() creates a file directory. The disadvantage of this function is that it can only create a folder under an existing path. If your File object path does not exist on the computer, the creation will fail. And using file.mkdirs() even if the file path does not exist, the function will automatically create the corresponding folder directory to ensure the successful creation of the file object.

It is recommended to use mkdirs() to create folders

	public void creatnewfile(String path) {// Create a new file\directory
		File file = new File(path);
		if (file.exists()) { //Determine whether the file in this path exists
			System.out.println("This file already exists!");
			return;
		}
		System.out.println("Create a file/directory under this path?");
		System.out.println("Enter 1 to create a file directory and enter 2 to create a file");

		Scanner scanner = new Scanner(System.in);
		int j = scanner. nextInt();
		if (j == 2) {
			try {
				file.createNewFile();//Create a file
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
		} else {
			file.mkdirs();//Create a directory
		}
	}

  file.delete() can delete files/folders. Although the delete() function can delete files, it can only delete empty directories when deleting folders. If there are files under the folder you want to delete / folder will fail to delete

  If you want to delete such a folder, you can use dfs to traverse the file directory + delete() to achieve

    public  boolean deleteFile(String path) { // Delete file|directory (continuous deletion) 
        File file = new File(path);
         if (! file.exists()) {
            System.out.println( "The file does not exist!" );
             return  false ;
        }        
        dfsdelete(path);
        return true;
    }

    public void dfsdelete(String path) {
        File file = new File(path);
         if (file.isFile()) { // If the file object is a file, delete it directly 
            file.delete();
             return ;
        }
        // When file is a folder, first get the string array of the corresponding file under the folder, and call itself recursively to achieve depth-first deletion 
            String [] list= file.list();
             for ( int i = 0; i < list. length; i++ ) {
                dfsdelete(path+File.separator+list[i]);
                
            } // When all files in the folder are deleted, this folder is already an empty folder, you can use delete() to delete 
            file.delete();
         return ;
    }
    

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324891458&siteId=291194637
Recommended